Search code examples
c++pointersinitializationundefined-behaviormemory-access

The initialization of ListNode


I have a question about the initialization of ListNode, if I just announce a ListNode pointer, why can't I assign its next value like showed in the code.

struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(nullptr) {}
};

ListNode* tmp;
tmp->next = nullptr;// This is wrong, why is that?

ListNode* tmp2 = new ListNode(1);
tmp2->next = nullptr;// This is right, what cause that?

I just try to announce a ListNode pointer and assign its next value to nullptr. But after I announce a pointer with new function, it goes right. Why?


Solution

  • A pointer is a box that can hold the address of an object

     ListNode* tmp;
     tmp->next = nullptr;// This is wrong, why is that?
    

    Here you created the box (tmp) but did not put the address of an object in it. The second line says - "at offset 4 from the address stored in tmp please write 0", well there is no valid address in the box so this fails.

    In the second example

    ListNode* tmp2 = new ListNode(1);
    tmp2->next = nullptr;// This is right, what cause that?
    

    You say

    "Please make a new ListNode object"
    "Put its address in the box called tmp2"
    "at offset 4 from the address stored in tmp2 please write 0"
    

    That can work, becuase the box tmp2 points somewhere valid