Note that there are some explanatory texts on larger screens.

plurals
  1. POHow could pairing new[] with delete possibly lead to memory leak only?
    primarykey
    data
    text
    <p>First of all, using <code>delete</code> for anything allocated with <code>new[]</code> is undefined behaviour according to C++ standard.</p> <p>In Visual C++ 7 such pairing can lead to one of the two consequences.</p> <p>If the type new[]'ed has trivial constructor and destructor VC++ simply uses <code>new</code> instead of <code>new[]</code> and using <code>delete</code> for that block works fine - <code>new</code> just calls "allocate memory", <code>delete</code> just calls "free memory".</p> <p>If the type new[]'ed has a non-trivial constructor or destructor the above trick can't be done - VC++7 has to invoke exactly the right number of destructors. So it prepends the array with a <code>size_t</code> storing the number of elements. Now the address returned by <code>new[]</code> points onto the first element, not onto the beginning of the block. So if <code>delete</code> is used it only calls the destructor for the first element and the calls "free memory" with the address different from the one returned by "allocate memory" and this leads to some error indicaton inside HeapFree() which I suspect refers to heap corruption.</p> <p>Yet every here and there one can read false statements that using <code>delete</code> after <code>new[]</code> leads to a memory leak. I suspect that anything size of heap corruption is much more important than a fact that the destructor is called for the first element only and possibly the destructors not called didn't free heap-allocated sub-objects.</p> <p>How could using <code>delete</code> after <code>new[]</code> possibly lead only to a memory leak on some C++ implementation?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload