Possible Duplicate:
How does delete[] “know” the size of the operand array?
In the following sample code :
int* p = new int[10];
delete[] p;
how does it know how many elements are to be deleted ?
I heard that this info is stored in a kind of header before the start of the table that have been allocated or somewhere else – but in this case, why can’t we access this value with a function like size(p) which would return 10 ? Is-there any particular reason for it ? What other informations are stored in these headers ? Is it OS specific? Compiler specific ?
Thanks
It’s totally unspecified, and different implementations do it
differently. Typically, the information isn’t even available if the
type doesn’t have a destructor.
Note that there are two different information managed behind the scenes:
how much memory has been allocated, and how many elements have
destructors which need to be called. If there is no destructor, only
the first is necessary, and there’s not necessarily a one to one mapping
between the first and the number of elements: on a lot of systems, for
example, alignment constraints will mean that
new char[1]andnew char[2]will allocate the same ammount of memory.