Alex
Alex

Reputation: 213

C - Code after 'if' (and inside a 'while') does not execute

A bit of background for this question, I have a linked list with names, in which I wan't to find a user input name. For convenience purposes, I copy the name (if found) to the same buffer, like so:

  aux = filtCountriesHead;  //head of my list
  while (aux != NULL){
    if (strstr(aux->data.name, buffer) != NULL){
      strcpy(buffer, aux->data.name);
      foundName = 1;
      break;
    } 
      aux = aux->next;  //this is skipped for some reason
  }

When I run this, it enters an infinite loop, because it does not execute the aux = aux->next line, which I found by running in the debugger. It doesn't execute anything in the 'if' (and even if it did, the 'break;' would make it exit the cycle, not run it again) so I'm all out of ideas. Anyone have an explanation?

Thanks in advance!

Upvotes: 0

Views: 79

Answers (1)

k_ssb
k_ssb

Reputation: 6272

Without more data, such as observations about aux's values, there is no way to be sure about the core issue. But here's a likely explanation...


If you observe an infinite loop where aux = aux->next; appears to do nothing, that must mean aux->next equals aux, i.e., aux points to itself. Typically the tail of a linked list points to NULL instead.

Of course, the cyclic list structure would need to be fixed elsewhere, since the list isn't being created in the provided code.

Upvotes: 1

Related Questions