Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: K&R do include the example, but they clearly know right from wrong whereas the original left the impression that this was a necessary errata to their book.

...

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
bgColor#FFCCCC
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.

...