Search code examples
c++pointersheap-memorynew-operatorstack-memory

C++ what exactly does new <datatype>(<value>) do?


In this code:

int * p = new int(44);

p is allocated on the heap and the value it points to is 44; but now I can also do something like this:

p[1] = 33;

without getting an error. I always thought

int * p = new int(44);

was just another way of saying "P is allocated on the heap and points to an address containing 44" but apparently it makes p a pointer to an array of ints? is the size of this new array 44? Or is this result unusual.


Solution

  • You were right: P is allocated on the heap and points to an address containing 44. There's no array allocated. p[1] = 33; is what they call "undefined behavior". Your program might crash, but it's not guaranteed to crash every single time you do this.