memory deallocation [duplicate]
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 ca开发者_如何转开发se, 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]
and new char[2]
will allocate the same ammount of memory.
The bookkeeping information kept by the allocator is most definitely compiler and allocator specific. C++ allows you to replace the built in allocator with your own, both globally and per-class. There's no standard API for 'peeking' into this information.
This is an almost duplicate question of this question
The details of how this is implemented will be compiler specific.
As for the last point about why we can't ask for size(p) - well I guess the allocator stores the amount of memory only, not details of the array type. Same as C's sizeof(). It wouldn't return 10 for the example shown, but how many bytes are required to store 10 standard ints on your platform.
Hope this helps.
精彩评论