Recently I got tangled into this problem in my code - Calling a vector
destructor 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. Of course, we know that we will end up in trouble. But I have really not given a thought WHY!
When we allocate an array of items e.g. OurClass pa[] = new[5] pa()
, the compiler actually allocates the necessary amount of memory, calls the constructors 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 destructors.
Now I think I don’t need to 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 The Old New Thing blog. Adam Nathan has explained it well with the compiler generated assembly and a bit of excellent code for the destructor.
What if we do a scalar delete on a vector pointer, there is less harm, you do not deallocate 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.