Memory allocation when creating objects in C ++

A different size of memory allocation is observed when creating an object in 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 8 bytes,

c2 allocated 8 * 2 + 4 bytes;

c3 is allocated 8 * 2 * 2 + 4 bytes.

Why are c2 and c3 using 4 more bytes?

+5
source share
3 answers

Remember that C ++ separates memory allocation and object expression. By default, an array-new expression T * p = new T[N];allocates enough memory for objects Nand constructs these objects. At the other end delete[] p;should call the destructor of all these elements, and then free the memory.

, , . -, ++ , N * sizeof(T). , p N, p , . (, p , .)

. ; , Itanium ABI ( cookie) , new T[N] :

+- alignof(T) --+-- sizeof(T) --+-- sizeof(T) --+-- sizeof(T) --+-- ...
| ***** [8B: N] |  1st element  |  2nd element  |  3rd element  |  .....
+---------------+---------------+---------------+---------------+-- ...
A               A
|               |_ result of "new T[N]"
|
|_ value returned "operator new[]()"
+8

( [expr.mew]):

, , std::size_t. ; , .

, , .

, , , , , , .

(: , )

+4

Many compilers use 4 bytes before returning a pointer from new [] to store the number of objects that are actually allocated. It depends on the implementation and it is important to remember that pointer arithmetic, which takes you outside the memory allocated by you, leads to undefined behavior

+3
source

All Articles