Search code examples
c++arraysmemorymemory-managementdynamic-memory-allocation

Is memory sequentially allocated when using new in C++?


Lets say that we allocate memory for 5 variables of type int using the following: int* ptr = new int[5]; Then if I am right the addresses of the allocated memory should be random? For example: If the address of &ptr[0] is let's say is 0x7fffa07f7560 then the address for &ptr[1] should be random instead of being 0x7fffa07f7564.

Only when we allocate the memory in the stack using int array[5]; should we get sequential addresses which are 4 bytes apart.


Solution

  • Memory addresses of unrelated memory blocs are unspecified and should be seen as an implementation detail. But int *ptr = new int[5] allocates a single bloc containing an array of 5 integers. And addresses in an array are expected to be consecutive... (in fact the C standard mandates they are.)

    So we have the following equalities:

    • &(ptr[1]) == &(ptr[0]) + 1 per pointer arithmetics
    • (void *) &(ptr[1]) == ((void *) &(ptr[0])) + sizeof(int) for byte addresses