FAQ 12.19 After pnew Fredn , how does the compiler know that there are n objects to be destructed during delete p ?

FAQ 12.19 After p = new Fred[n], how does the compiler know that there are n objects to be destructed during delete[] p?

Warning: This FAQ is quite low level. The only people who really need to worry about this level of detail are those in extremely performance sensitive situations where CPU cycles are at a premium. Of course it also might be interesting to those who are just plain curious...

Whenever someone says Fred* p = new Fred[n], the runtime system is required to store the number of objects, n, in a place that can be retrieved knowing only the pointer, p. The compiler can use any technique it wants to use, but there are two popular ones.

  1. The code generated by p = new Fred[n] might store the number n in a static associative array, where the pointer p is used as the lookup key and the number n is the associated value. For example, using the standard map template (see FAQ 28.14), this associative array might be map<void*,size_t>. The code generated by delete[] p would look up the pointer in the associative array, would extract the associated size_t, then would remove the entry from the associative array.

  2. The code generated by p = new Fred[n] might allocate an extra sizeof(size_t) bytes of memory (possibly plus some alignment bytes) and put the value n just before the first Fred object. Then delete[] p would find n by looking at the fixed offset before the first Fred object (that is, before *p) and would deallocate the memory starting at the beginning of the allocation (that is, the block of memory beginning the fixed offset before *p).

Neither technique is perfect. Here are a few of the tradeoffs.

  1. The associative array technique is slower but safer: if someone forgets the [] when deallocating an array of things, (a) the entry in the associative array would be a leak, and (b) only the first object in the array would be destructed. This may or may not be a serious problem, but at least it might not crash the application.

  2. The overallocation technique is faster but more dangerous: if someone says delete p where they should have said delete[] p, the address that is passed to operator delete(void* p) would not be a valid heap allocation it would be at least sizeof(size_t) bytes after a valid heap allocation. This would probably corrupt the heap. Bang, you're dead.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net