In C++, when you dynamically allocate an array of int
, are the values of the int
s undefined or initialized to 0?
int *array = new int[50];
In C++, when you dynamically allocate an array of int
, are the values of the int
s undefined or initialized to 0?
int *array = new int[50];
If you write
then the values in the array can contain anything, but if you write
then you will be calling the "default constructor" and everything will be 0.
They will be undefined. Just garbage depending on what was in those locations before you initialized it
In C/C++, allocate an object in memory means simply reserving a number of memory blocks to that object. The initial value is basically what was present in those blocks which is most of the time random values.
You need to assume it is garbage, even though it may often (especially in debug builds) be initialised to zero or some other predefined value indicating uninitialised memory (usually some HexSpeak value if zero is not used).
E.g. see http://www.nobugs.org/developer/win32/debug_crt_heap.html#table
It is completely undefined by the standard, and really just depends on your OS and compiler. In some compilers, it just uses whatever the OS gave you, and in some OSes that will be 0s, others garbage, and others something else. Or the compiler could automatically insert an invisible
memset
after amalloc
ornew
. But in any case, the point is, never rely on the value. Even if your current version of your compiler makes it 0s, say, that might change in a future version, and probably won't be true on another compiler.The term is uninitialized. But it depends how you initialize the array. You could value-initialize it:
and the values would be 0.
If you leave it uninitialized, you can't know what values are there because reading from them would be undefined behavior.