I am reading Chapter 17 of C Primer Plus, and here is the code segament to free a linked list in the book:
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
In the while statement, how could the “current” variable get the next value after already been freed? I searched for some code segaments to free linked lists on the web, and they seem to use two pointers in the while statement in order to avoid the previous problem.
However, if this is a bug, I couldn’t find this in errata. So any comments?
Thanks!
Yes, it’s clearly a bug. Accessing heap memory that has been
free()d invokes undefined behavior. Bad book!The proper way is to buffer the
nextpointer before callingfree():Notes:
currentand updateheadinstead.