Jonathan Swiecki Jonathan Swiecki - 2 months ago 11x
C Question

How to clear a linked list using double pointer?

Hi I'm trying to make a function that clears a linked list that

will point to, then the node
should be freed and the pointer
set to

I'm having trouble grasping double pointers and can't get this to work correctly.


You have to move to the next list element before you delete the node. Otherwise you are accessing memory that has been freed.

while( *first != NULL )
    temp = *first;
    *first = temp->next;

Be aware that because you're trashing the whole list, *first is going to eventually be NULL. So you can use a single-pointer (just like temp) to traverse your list, and then set *first = NULL at the end. That saves an extra pointer indirection, which arguably is wasteful of CPU in this case.

[edit] What I mean is:

struct node *curr = *first;
struct node *prev;            

while( curr != NULL )
    prev = curr;
    curr = curr->next;

*first = NULL;

Generally, I find that the less pointer dereferencing you have going on, the easier the code is to understand at a glance.