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?

Was it helpful?

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);
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top