Search code examples
clinked-listnodes

Delete all nodes in a linked list (in c)


I'm solving exercise 17.7 on page 454 in the book C Programming: A Modern Approach (http://knking.com/books/c/). The question is below:

The following loop is supposed to delete all nodes from a linked list and release the memory they occupy. Unfortunately, the loop is incorrect. Explain what's wrong with it and show how to fix the bug.

for (p = first; p != NULL; p = p->next)
    free(p);

My solution is this:

struct node *next_node;
p = first;

while (p != NULL) {
    next_node = p->next;
    free(p);
    p = next_node;
}

Is my answer correct?


Solution

  • Your approach is fine, but if all you provide is a corrected version, your answer is incomplete: you should first explain why p = p->next has undefined behavior once p has been freed with free(p).

    You might also define next_node with a tighter scope, inside the loop:

    p = first;
    while (p != NULL) {
        struct node *next_node = p->next;
        free(p);
        p = next_node;
    }
    

    Here is an alternate correction as a single statement for consistency with the code fragment in the question.

    for (p = first; p != NULL; ) {
        struct node *next_node = p->next;
        free(p);
        p = next_node;
    }