Search code examples
c++new-operator

Does new[] allocate memory contiguously?


When I use the new[] keyword (or new-operator), does it allocate memory contiguously?

int* arr = new int[10];

I mean, is there any guarantee, that arr[0] and arr[1] are closely placed, and I can iterate through the arr using pointer increments? If so, does this behavior save with structs and classes instead of int?


Solution

  • The C++ standard absolutely guarantees this.

    arr[0] through to arr[9] are contiguous with no padding allowed between elements. Pointer arithmetic is valid in the allocated region. You are allowed to set a pointer to arr + 10, but don't dereference it.

    This applies to any class. The amount of memory allocated per element is sizeof(Y) where Y is the class or plain old data type.