0

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;
Kon
  • 4,023
  • 4
  • 24
  • 38
  • 5
    Well, in the first case you don’t initialize it. It can be any value. –  Jan 30 '19 at 18:57
  • 2
    Possible duplicate of https://stackoverflow.com/questions/13423673/what-is-indeterminate-value – François Andrieux Jan 30 '19 at 18:57
  • 1
    @dyukha It's not so much that is can have any value. It's value is indeterminate. Reading it is UB which goes beyond simply not knowing what the value is. – François Andrieux Jan 30 '19 at 19:01
  • @FrançoisAndrieux, Dereferencing it is UB. Reading it isn't. – Sid S Jan 30 '19 at 19:07
  • As far as I can tell in the standard, only "[o]bjects with static or thread storage duration are zero-initialized, see 6.8.3.2." As this is neither of those, it has an indeterminate value (Section 6.6.4). – callyalater Jan 30 '19 at 19:07

2 Answers2

1

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.

Kon
  • 4,023
  • 4
  • 24
  • 38
0

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.

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64