Search code examples
cpointersallocation

Linked List- NULL pointer check?


In this code snippet for adding to a Linked List, what is if (List==NULL) doing? I tried to throw some inputs at it to see if I could engage that statement with no luck. What type of input would work?

main()
{
    struct Node *List;
    List = NULL;

    append (&List, 5);
}



void append(struct Node **List, int num)
{
    if (List == NULL)
    {
        return;
    }


    if (*List == NULL)
    {
        *List = malloc(sizeof(struct Node));
        (*List)->data = num;
        (*List)->next = NULL;

    }
   //some additional cases edited out for brevity
}

Solution

  • If for whatever reason you (or the user of your library) call append(NULL,42); then, thanks to the if(List == NULL) check, your program won't crash. Otherwise (if you remove the if(List == NULL) check) it is undefined behavior and practically segmentation fault would happen. That check is an instance of defensive programming.

    In principle it looks like append is intended to be called as append(&somevar, someint) but this is not documented, so adding the extract check (which is extremely cheap at runtime!) is worthwhile.