Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Alexey Larionov Avatar asked Sep 15 '17 14:09

Alexey Larionov


2 Answers

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.

like image 189
Bathsheba Avatar answered Oct 25 '22 14:10

Bathsheba


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.

like image 27
463035818_is_not_a_number Avatar answered Oct 25 '22 14:10

463035818_is_not_a_number