Friday, May 25, 2007

Write a C program to free the nodes of a linked list

Before looking at the answer, try writing a simple C program (with a for loop) to do this. Quite a few people get this wrong.


This is the wrong way to do it


struct list *listptr, *nextptr;
for(listptr = head; listptr != NULL; listptr = listptr->next)
{
free(listptr);
}


If you are thinking why the above piece of code is wrong, note that once you free the listptr node, you cannot do something like listptr = listptr->next!. Since listptr is already freed, using it to get listptr->next is illegal and can cause unpredictable results!



This is the right way to do it


struct list *listptr, *nextptr;
for(listptr = head; listptr != NULL; listptr = nextptr)
{
nextptr = listptr->next;
free(listptr);
}
head = NULL;


After doing this, make sure you also set the head pointer to NULL!

4 comments:

  1. Wrong implementation because just a freed pointer can not be a NULL at any point of time but an invlid pointer.
    Right one is:
    struct list *listptr, *nextptr;
    listptr = head;
    while (listptr != NULL)
    {
    nextptr = listptr;
    listptr = listptr->next;
    free(nextptr);
    }
    nextptr = NULL;

    ReplyDelete
  2. Wrong implementation because just a freed pointer can not be a NULL at any point of time but an invlid pointer.
    Right one is:
    struct list *listptr, *nextptr;
    listptr = head;
    while (listptr != NULL)
    {
    nextptr = listptr;
    listptr = listptr->next;
    free(nextptr);
    }
    nextptr = NULL;

    ReplyDelete
  3. Basavaraj : The above code is also correct because:
    here in for statement
    for(listptr = head; listptr != NULL; listptr = nextptr)

    it is again assiging a value as listptr = nextptr.

    note:free(listptr) will free the adress containing by listptr not the pointer listptr

    ReplyDelete
  4. Hi, I would like to subscribe for this web site to get
    newest updates, therefore where can i do it please help out.


    My website; waist to hip ratio calculator

    ReplyDelete