Search code examples
clistdealloc

C - linked-lists for loop doubts


I am unsure on which way to dealloc my list of Item. Each list has a first and last item, and each item is linked to a nextItem until it is null.

for(myItem=list.firstItem; myItem!=list.lastItem; myItem=myItem->nextItem)
    dealloc(myItem);

or

for(myItem=list.firstItem; myItem!=NULL; myItem=myItem->nextItem)
    dealloc(myItem);

myItem->nextItem = NULL if myItem=list.lastItem.

I am unsure if using the first declaration of the for will dealloc all of myItem or if the lastItem will not be dealloc. (I believe this is what will happen.) On the other hand, i am unsure if the second declaration will make everything crash/not work properly when you assign to NULLa myItem.


Solution

  • Both programs have undefined behavior, because you dereference myItem pointer after it has been deallocated. This is not allowed, and may crash your program.

    A proper way to deallocate a linked list is with a while loop, when you get the next pointer first, and only then deallocate the node:

    ItemNode *myItem = list.firstItem;
    while (myItem != NULL) {
        ItemNode *tmp = myItem;
        myItem = myItem->nextNode;
        dealloc(tmp);
    }