Suppose I’m a C++ compiler, and I implement my memory management like this: I prepend every block of reserved memory with the size of the memory, in bytes. Something like this;
| size | data ... |
^
pointer returned by new and new[]
Note that, in terms of memory allocation, there is no difference between new
and new[]
: both just allocate a block of memory of a certain size.
Now how will delete[]
know the size of the array, in order to call the right number of destructors? Simply divide the size
of the memory block by sizeof(T)
, where T
is the type of elements of the array.
Now suppose I implement delete
as simply one call to the destructor, followed by the freeing of the size
bytes, then the destructors of the subsequent elements will never be called. This results in leaking resources allocated by the subsequent elements. Yet, because I do free size
bytes (not sizeof(T)
bytes), no heap corruption occurs.