I'm trying to implement a linked list but when I allocate memory for one note, the pointer inside it is not NULL.
Here is my struct
template <typename T>
struct Node {
T value;
Node* next;
};
and I allocate memory for a note
first = new Node<T>;
the first->next is not NULL. This forces me to explicitly assign that note to NULL. It really confused me. But why did this happened ?
The address of the uninitialized pointer is undefined until you set it. When you call new Node<T>
you are invoking default-initialization
Default initialization is performed in three situations:
- when a variable with automatic, static, or thread-local storage duration is declared with no initializer.
- when an object with dynamic storage duration is created by a new-expression with no initializer or when an object is created by a new-expression with the initializer consisting of an empty pair of parentheses (until C++03)
- when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.
The effects of default initialization are:
- If T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object.
- If T is an array type, every element of the array is default-initialized.
- Otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
To have the struct
value-initialized you would need to call it as
first = new Node<T>();
Note that the latter part of comment 2 (the non-bold part) is no longer true as of C++11 and later, now the following is true:
§8.5 Initializers
An object whose initializer is an empty set of parentheses, i.e.,
()
shall be value-initialized.