Tom
Tom

Reputation: 6971

Malloc seemingly using less memory than new[]

Could there be any reason why:

new X[n];

would consume more memory as compared to:

X* x = reinterpret_cast<X*>(malloc(n * sizeof(X))
for(X* p = x; p != x + n; ++p)
    new (p) X();

for multiple copies of multiple n's?

I am seeing evidence of this.

Upvotes: 0

Views: 126

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477100

Of course: Array-new is allowed to allocate more memory than just the space for the objects, and usually will do so. When you say delete [] x;, how would the implementation know how many destructors to call?

See 5.3.4/10:

A new-expression passes the amount of space requested to the allocation function as the first argument of type std::size_t. That argument shall be no less than the size of the object being created; it may be greater than the size of the object being created only if the object is an array.

The Itanium ABI is specific about the use of array cookies:

|<-- offset -->|
+--------------+----------+----------+---------+---------+
|(padding)  N  |   a[0]   |   a[1]   |   ...   |  a[N-1] |
+--------------+----------+----------+---------+---------+
^              ^
|              +---- T * a = new T[N]
|
+----  return value of `operator new(sizeof(T) * N + offset)`

Upvotes: 5

Related Questions