0

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
}
Ragnar
  • 15
  • 4

2 Answers2

0

If you pass NULL as the List pointer the program will crash when you dereference it in:

if (*List == NULL)

So you must check that that function wasn't called with NULL as the parameter

antonpuz
  • 3,256
  • 4
  • 25
  • 48
0

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.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • ...ah that was quite simple. I feel a little stupid now... I might have been over thinking it I guess, thanks though. – Ragnar Mar 10 '15 at 09:43