Jonathan Swiecki Jonathan Swiecki - 4 months ago 28
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

*first
will point to, then the node
**first
should be freed and the pointer
*first
set to
NULL
.

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

Answer

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;
    free(temp);
}

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;
    free(prev);
}

*first = NULL;

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

Comments