During my work on bringing code from windows-only platform to the GNU compiler I noticed some strange behavior with an uninitialized pointer to a vector.
The corresponding code looks like this:
typedef vector<IPeer*> Network;
// [...]
Network* m_network;
// [...]
if (m_network == NULL) // <-- this is the strange part
m_network = new Network();
The marked line is making me sad. After declaring my vector it was NULL when I compiled it on my Windows machine. After moving the code to my Mac using GNU Compiler (I'm compiling on g++-5
with -std=c++11
) my vector doesn't seems to be NULL after declaration anymore. The marked line is skipped.
Is this an c++ standard implementation issue or where does this strange behavior came from?
Uninitialized pointer has undetermined behaviour. Could be NULL
or not, depending on the compiler (and, even for a specific compiler, Release
and Debug
binaries may have a different behaviour) and/or the memory state (see comments to this post).
It is recommended to always initialize them. Never expect an uninitialized variable to have a specific value (it's true for pointers, but also true for other types like int
, bool
that may take different default initialization values depending on the compiler/target).
It's actually hard to know what will be the value of an unitialized variable, and in many cases it is not deterministic.