CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Removing an item from the head our list

Removing items from the head of our list, is much easier.

Of course, we again need to be careful about the case of the empty list:


char *remove_item(void)
{
    LISTITEM *old = list;
    char     *string;

    if(old == NULL) {
        fprintf(stderr, "cannot remove item from an empty list\n");  
        exit(EXIT_FAILURE);
    }

    list   = list->next;
    string = old->string;
    free(old);

    return string;
}

Notice that we return the string (data value) to the caller, and deallocate the old node that was at the head of the list.

We say that the caller now owns the storage required to hold the string - even though the caller did not initially allocate that storage.

It will be up to the caller to deallocate that memory when no longer required.
Failure to deallocate such memory can lead to memory leaks, that may eventually crash long running programs.

 


CITS2002 Systems Programming, Lecture 19, p11, 3rd October 2023.