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 o...
Another effective [debugging] technique is to explain your code to someone else. This will often cause you to explain the bug to yourself. Sometimes it takes no more than a few sentences, followed by an embarrassed "Never mind. I see what's wrong. Sorry to bother you." This works remarkbly well; you can even use non-programmers as listeners. - From "The Practice of Programming" by Brian W Kernighan & Rob Pike.