Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading