1

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 ?

thinh
  • 21
  • 4
  • 2
    This happened because C++ doesn't automatically initialise everything for you. The fact that you're surprised by this suggests that you've jumped ahead of the basics straight into templates. Even if you have previous programming experience, it's a good idea to study the fundamentals first (that's where the big surprises are). – molbdnilo Aug 18 '15 at 12:20

2 Answers2

7

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:

  1. when a variable with automatic, static, or thread-local storage duration is declared with no initializer.
  2. 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)
  3. 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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
4

It has some garbage value. You should initialize it in constructor.

Node() : next(0), value(T()) {}

or you can just use

first = new Node<T>();

for value-initialization.

ForEveR
  • 55,233
  • 2
  • 119
  • 133