Alexey S. Larionov
Alexey S. Larionov

Reputation: 7937

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?

Upvotes: 10

Views: 1519

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122830

Yes the elements are guaranteed to be located in consectuive memory (independent of their type). When you call new[] you get an array and actually the only way to access the elements is via pointer arithmetics.

Consider what arr[i] actually means:

arr[i]

is really just a short form of

*( ( arr ) + (i) )

A quirky sideeffect of this, is that for an array arr and an index i

i[arr]

is exactly the same as arr[i] (though you would only write this if you want to confuse your coworkers).

However, note that [] can be overloaded and in that case it can do whatever the implementation chooses. Nevertheless, also an array allocated with new[] that has an overloaded oeprator[] will have its elements in consecutive memory.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234785

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.

Upvotes: 16

Related Questions