Search code examples
c++data-structureslinked-liststructuredynamic-memory-allocation

Why are we checking if temp == null?


This code is for implementation of linked list.

node *single_llist::create_node(int value)
{
    struct node *temp, *s;
    temp = new(struct node); 
    if (temp == NULL)
    {
        cout<<"Memory not allocated "<<endl;
        return 0;
    }
    else
    {
        temp->info = value;
        temp->next = NULL; 
        return temp;
    }
}
  1. Here, why are we checking if temp == NULL. I can't think of any case where this can happen

  2. Also to exit from if, why are we returning 0 since the return type is node?


Solution

    1. As the message clearly says, this is in case the request to allocate memory fails. (Exactly how this might happen is irrelevant; it is possible, so the code should handle it.)
    2. The author is assuming that NULL==0, which is often true, but not necessarily so, and (as we both seem to think) is a bad assumption to make.