R@M3$H.NBlog

delete[] --- How does Compiler know how many Objects to Delete

26 January, 2013 - 1 min read

delete[] p

The run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the pointer, p. There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:

  • Over-allocate the array and put n just to the left of the first Fred object.

new char[10] could allocates a few extra bytes, put the number of elements at the beginning, then return the pointer to the first element after that. delete[] could then look behind the pointer at the stored count

  • Use an associative array with p as the key and n as the value.

store the equivalent of std::map<void*, size_t>, and new T[n] would create a key with the returned pointer, and a value with the count. delete[] would look up the pointer in this map