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];
The term is uninitialized. But it depends how you initialize the array. You could value-initialize it:
int *array = new int[50]();
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.
If you use vectors instead of arrays, you will get an initial value of 0 for all elements:
std::vector<int> v(50);
If you want a different default value, you can specify one:
std::vector<int> v(50, 42);
An additional benefit of vectors is that you don't have to manually release the underlying array.
To answer your question no.. But there is a way to set default values. Try:
int *arr = new int[SIZE]() ;
The above is C++ standard but may not work on all compilers. The safe bet would be to use a loop and initialize it to a default value of your choice.
for(int i=0; i < SIZE; i++)
{
arr[i] = 1; //1 being my default value
}
EDIT: As others have pointed out even better: memset
They will be undefined. Just garbage depending on what was in those locations before you initialized it
If you write
int *array = new int[50];
then the values in the array can contain anything, but if you write
int *array = new int[50]();
then you will be calling the "default constructor" and everything will be 0.
They are neighter, they contain whatever data was there before the allocation.
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 a malloc
or new
. 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.