Checking if a pointer in a struct is null

5.5k views Asked by At

I have a very simple struct

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

and i am trying to always add to the pNext that is not null.

Node *head;


void add(int nValue){
    if (!head)
    {  
        Node *node = new Node;
        node->nValue=nValue;
        head = node;
    }
    else
    {
        add(head,nValue);
    }
}

void add(Node *pNode, int nValue){
    if (!(pNode->pNext))
    {
        Node *node = new Node;
        node->nValue=nValue;
        pNode->pNext = node;
    }
    else
    {
        add(pNode->pNext,nValue);
    }
}

When I call add(10); the first time, it sets the head pointer to an instantiated node. but when I call the method again add(9); i get an "Access violation reading location 0xCDCDCDCD".

My question is, how can i check if the pNext node is assigned an address or not? i tried using the == nullptr but to no avail.

4

There are 4 answers

0
Johny On BEST ANSWER

You didn't initialize the pNext pointer, so it has probably some random value.

Try to use this declaration :

 struct Node{
   //Default constructor, which sets all values to something meaningful
   Node():pNext(nullptr), nValue(0) {}

   Node* pNext;
   int nValue;
 };
0
sara On

Change your code to:

Node *head;


void add(int nValue){
    if (!head)
    {  
        Node *node = new Node;
        node->nValue=nValue;
        **node->pNext =NULL;**
        head = node;
    }
    else
    {
        add(head,nValue);
    }
}

void add(Node *pNode, int nValue){
    if (!(pNode->pNext))
    {
        Node *node = new Node;
        node->nValue=nValue;
        **node->pNext =NULL;**
        pNode->pNext = node;
    }
    else
    {
        add(pNode->pNext,nValue);
    }
}
0
molbdnilo On

You're forgetting both to set head to NULL to begin with, and to set pNext to NULL in your newly created nodes.

As opposed to e.g. Java, C++ doesn't automatically initialize variables to 0 (or the equivalent).

0
Sebastian Steger On

you need to initialize pNext properly by setting it to nullptr explicitly in node's constructor. 0xCDCDCDCD is always in indicator for accessing uninitialized memory.