The different size of memory allocation is observed during the object creation on class C below,
class C {
int i;
int j;
};
void f() {
C *c = new C;
C *c2 = new C[2];
C (*c3)[2] = new C[2][2];
}
c is allocated with 8 bytes;
c2 is allocated with 8*2+4 bytes;
c3 is allocated with 8*2*2+4 bytes.
Why does c2 and c3 aquire 4 more bytes?
Remember that C++ separates memory allocation and object expression. The default array-new expression
T * p = new T[N];both allocates enough memory forNobjects and constructs those objects. At the other end,delete[] p;must call the destructor of all those elements, and then free the memory.While allocating and freeing memory is handled by the platform, and freeable memory is sufficiently well identified to the OS by a single pointer value, constructing and destroying objects is more complicated. The number of actual objects must be stored somewhere, and to that end, the standard permits a C++ implementation to request more memory than
N * sizeof(T). It is true that the pointerpwill always point to the beginning of the array ofNobjects, butpdoes not have to be the same pointer that was returned by the underlying memory allocator. (In fact,pis guaranteed to be precisely the value of the underlying allocation result offset by the excess amount of memory.)The details are entirely left up to the implementation. Some platforms provide additional guarantees, though; for example, the Itanium ABI (which calls the extra data “array cookie”) says that the memory for
new T[N]will be laid out as follows: