...
Wiki Markup |
---|
This example from Kernighan & Ritchie \[[Kernighan 88|AA. C References#Kernighan 88]\] shows items being deletedillustrates both the incorrect and correct techniques for deleting items from a linked list. Because The incorrect solution, clearly marked as wrong in the book, is bad because {{p}} is freed before the {{p->next}} is executed, so {{p->next}} reads memory that has already been freed. |
Code Block | ||
---|---|---|
| ||
for (p = head; p != NULL; p = p->next) { /* WRONG */ free(p); } |
Compliant Solution
Kernighan & Ritchie also show the correct solution. To correct this error, a reference to p->next
is stored in q
before freeing p
.
...