Get the size of a dynamic array

Dear programmers,

I remember in C++, when a dynamic array is allocated, the size of this array is stored right before the array in memory. Therefore compiler knows exactly how long, when this array is deleted.

Do all compilers store the size this way? Is it a safe method to get the size of a dynamic array?

Here is a example code, it works fine on Visual Studio 2012.

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
#include <iostream>

using namespace std;

class dummy
{
public:
	dummy()
	{
		cout<<"dummy created"<<endl;
	}
	~dummy()
	{
		cout<<"dummy passed away"<<endl;
	}
};

int main()
{
	dummy* pdummy = new dummy[10];
	int* pint = (int*)pdummy;
	--pint;
	cout<<"array size "<<*pint<<endl;
	delete[] pdummy;
	return 0;
}


Best regards,
MiMiChaCha
Last edited on
I do not advice to use such a trick because the C++ standard does not specify how the implementation shall allocate a memory. Moreover some applications can use a user-defined scheme for memory allocation.
That is what I'm worried, Thanks!
Topic archived. No new replies allowed.