Search code examples
cpointerslinked-listsingly-linked-listfunction-definition

Reference to non-NULL value NULL after assignment


I'm implementing a singly linked list using C.

struct Node 
{
    int nodeValue;
    struct Node* pNext;
};

struct Node* head;

void createList()
{
    head = (struct Node*)malloc(sizeof(struct Node));
}

void insertNodeAtBeginning(int value)
{
    struct Node* newNode;
    newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->nodeValue = value;
    struct Node* auxNode;

    if(head->pNext == NULL)
    {
        head->pNext = newNode;        
    }

    else
    {
        auxNode = head->pNext;
        head->pNext = newNode;
        newNode->pNext = auxNode;    //breakpoint set here
    }
}

I've set a breakpoint on line marked by the comment. The value of auxNode is non-NULL:

(gdb) p auxNode
$4 = (struct Node *) 0x5555555551db <createList+18>

However the value of newNode->pNext to which the auxNode is assigned is NULL:

(gdb) p newNode->pNext
$5 = (struct Node *) 0x0

Could anyone clarify this behavior? Thanks.


Solution

  • For starters the function createList does not make a sense.

    void createList()
    {
        head = (struct Node*)malloc(sizeof(struct Node));
    }
    

    You already created an empty list

    struct Node* head;
    

    Within the function data members nodeValue and pNext were not initialized,

    The function insertNodeAtBeginning also does not make a sense because at least it does not insert a node at beginning due to this code snippet

    if(head->pNext == NULL)
    {
        head->pNext = newNode;        
    }
    

    Moreover it invokes undefined behavior because the data member pNext of the node pointed to by the pointer head was not initialized. And again you forgot to initialize the data member pNext of the new node when head->pNext is equal to NULL.

    Remove the function createList and define the function insertNodeAtBeginning the following way

    int insertNodeAtBeginning(int value)
    {
        struct Node* newNode = malloc( sizeof( struct Node ) );
        int success = newNode != NULL;
    
        if ( success )
        {
            newNode->nodeValue = value;
            newNode->pNext = head;
            head = newNode;        
        }
    
        return success;
    }