Question

lets say I have a linked list( any kind , let just say singly linked list)

  for(current = head; current!=NULL; current=current->next)
       free(current);

Let's say this is my code , is there going to be any point at which this code might fail? or is there a safer approach to free the nodes?

Était-ce utile?

La solution

There is certainly a problem with this code: the for loop you are executing is equivalent to

current = head;
while (current!=NULL) {
   free(current);
   current=current->next;
}

That is you are accessing current after the free.

You should change this to

current = head;
while (current!=NULL) {
   tmp = current;
   current=current->next;
   free(tmp);
}

Autres conseils

Your code is unsafe as you do:

free (current);

then the for loop will execute:

current = current->next;

which evaluates current->next when current is free.

How about:

 for(current = head; current!=NULL;)
 {
     temp = current->next;
     free(current);
     current = temp;
 }

Also you can abbreviate that by:

 for(current = head; current;)
 {
     temp = current->next;
     free(current);
     current = temp;
 }

Well, look at the following step:

current = head;
current != NULL
free ( current );
current = current->next;

Do you see a problem? You are trying to go to next after freeing the memory allocated to current.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top