Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial Value of Dynamically-Allocated Memory in C++

In C++, when you dynamically allocate an array of int, are the values of the ints undefined or initialized to 0?

    int *array = new int[50];
like image 947
Brett George Avatar asked Nov 30 '22 02:11

Brett George


2 Answers

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.

like image 198
Luchian Grigore Avatar answered Dec 01 '22 14:12

Luchian Grigore


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.

like image 45
fredoverflow Avatar answered Dec 01 '22 15:12

fredoverflow