memory allocation operator new / delete, new [] / delete[]

Hello

I made a simple code.
Please analyse it and make debug !

My question is:
Why 16 bytes is allocated for 3 MyClass1 objects ??

sizeof(MyClass1) = 4

So for 3 objects need 12 bytes.

When I made debug I saw a_bytes = 16 in function
operator new[] ( size_t a_bytes ) !!!

WHY ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
struct CAlloc
{
	static void* operator new ( size_t a_bytes ) 
	{ 
		void *storage = malloc( a_bytes );
		if ( NULL == storage ) 
                    throw "allocation fail : no free memory";
		return storage;
	 }

 	static void operator delete ( void* a_ptr )	
 	{
 		free( a_ptr ); 
 	}

 	static void* operator new[] ( size_t a_bytes )	
	{
		void *storage = malloc( a_bytes );
		if ( NULL == storage )
                   throw "allocation fail : no free memory";
		return storage;
	 }

	static void operator delete[] ( void* a_ptr )	
	{ 
		free( a_ptr ); 
	}

};

//-----------------------------------
class MyClass1 : public CAlloc
{
public:

 	MyClass1()
 	{
		m_Data = 0;
 	}

 	~MyClass1()
 	{
 	}

private:

	int m_Data;

};

//-----------------------------------


int main ()
{
	// 4 bytes !!!  correct !!!
	int size = sizeof(MyClass1);

	// case1 1  
        // alloc 4 bytes ; correct !!!
	MyClass1* pObj1 = new MyClass1;
	delete pObj1;

	// case 2
        // I want to alloc memory for 3 objects 3 * 4 = 12 bytes !
	// but a_bytes is 16 bytes ???? 
	MyClass1* pObj2 = new MyClass1[3];
	delete [] pObj2;

    return 0;
}
In line 68, delete [] pObj2;, how does the program know how many elements are to be destroyed?
Topic archived. No new replies allowed.