title: Why can't I find the infinite loop in my C program to search in a linked list? The program works
body: <p>Here's my program for searching an element in a linked list. I am being told there is an infinite loop in my code. I don't know where. The program works on my end and it doesn't keep looping for me. I really can't figure it out. If anyone has any suggestions or ideas on what part of my code I should look at to fix the issue please let me know. I'm truly stumped. </p>
  
  <pre><code>struct node
  {
      int a;
      struct node *next;
  };
  
  
  void generate(struct node **head, int num)
  {
      int i;
      struct node *temp;
  
      for (i = 0; i &lt; num; i++)
      {
          temp = (struct node *)malloc(sizeof(struct node));
          temp-&gt;a = rand() % num;
  
          if (*head == NULL)
          {
              *head = temp;
              temp-&gt;next = NULL;
          }
          else
          {
              temp-&gt;next = *head;
              *head = temp;
          }
          printf("%d    ", temp-&gt;a);
      }
  }
  
  void search(struct node *head, int key, int index)
  {
      while (head != NULL)
      {
          if (head-&gt;a == key)
          {
              printf("Key found at Position: %d\n", index);
          }
  
          search(head-&gt;next, key, index - 1);
      }
  }
  
  void delete(struct node **head)
  {
      struct node *temp;
      while (*head != NULL)
      {
          temp = *head;
          *head = (*head)-&gt;next;
          free(temp);
      }
  }
  
  int main()
  {
      struct node *head = NULL;
      int key, num;
  
      printf("Enter the number of nodes: ");
      scanf("%d", &amp;num);
      generate(&amp;head, num);
      printf("\nEnter key to search: ");
      scanf("%d", &amp;key);
      search(head, key, num);
      delete(&amp;head);
  }
  </code></pre>