Do not delete [] a scalar pointer !!!

Recently I got tangled into this problem in my code – Calling a vector dtor for a scalar pointer. We all know that it is perfectly illegal to do that. For example, if we allocate something like this:-

OurClass *p = new OurClass();

and try to delete like this:-
delete []p;

then we are going to end up in trouble. Ofcourse we know that we will end up in trouble. But I have really not given a thought HOW ?

When we allocate an array of items eg. OurClass pa[] = new[5] pa(), the compiler actually allocates the necessary amount of memory, calls the ctors for each allocated class and also prefixes the block of memory of the ‘n’ items allocated with the number of items allocated.

NumItems | OurClassObject1 | OurClassObject2 | …… | OurClassObjectn

But pa always points to the first item in the allocation, thereby the item count prefix remains hidden. When we call delete[] pa, the compiler uses the item count prefix to delete the allocated objects and call the dtors.

Now i think i don’t need explain any further as what happens when i use delete []p, and what junk value will the compiler take from the memory location just before the memory location p believing it to be the item count.

I learnt this interesting information from OldNewThing Blog. Adam Nathan has explained it well with the compiler generated assembly and a bit of excellent code for the dtor.

And what if we do a scalar delete on a vector pointer, there is less harm, you do not unallocate the memory completely, you leave behind remnants of your allocated memory which you cannot reclaim.

Either way, it is better to be disciplined while programming.