Given an object, e.g. listNode.
If I initialize a pointer to an object with:
listNode* head_node;
How is this any different from
listNode* head_node = NULL;
Given an object, e.g. listNode.
If I initialize a pointer to an object with:
listNode* head_node;
How is this any different from
listNode* head_node = NULL;
In the first case listNode* head_node;
the compiler will allocate some memory to hold the pointer. That memory can contain any value (for example it could be some random value from when that location was used for something else) and, in fact, reading it will result in undefined behavior.
In the second case listNode* head_node = NULL;
, the compiler will allocate some memory to hold the pointer and then write NULL
to that location so the pointer is guaranteed to be NULL
.
One thing to note, you should use nullptr
as opposed to NULL
. See this answer for why.
In the first case, you are declaring a pointer variable. In the second case, you are declaring a pointer variable and initializing it to NULL
. Any variable that is declared but not initialized leads to undefined behaviour when you try to access the variable. This has nothing to do specifically with pointers, pointers are just like any other variable. For example, if you write int a;
and then you cout << a;
you will see that a
most likely has a random integer value written in it. But if you write int a = 0;
and then you cout << a;
you will see that a
is always 0 on any compiler on any machine. This is well defined behaviour as opposed to undefined behaviour.
I would discourage the use of raw pointers in your case, as you most likely want always them to be initialized to nullptr
, plus your listNode is most likely "owned" by the list itself. Try to use std::unique_ptr<listNode>
instead: it will both initialize you pointer to nullptr
by default and release the allocated memory when the pointer goes out of scope, meaning that if the head of the list will be deleted, all the other nodes in the list will automatically be deleted as well.