Deleting a pointer to an array allocated with new []
is "undefined behaviour". I'm just curious why the first delete
in the following code leads to heap corruption IF the destructor is defined, otherwise nothing happens (as I humbly expected). Tested with Visual Studio 8 and GNU GCC version 4.7.2 (http://www.compileonline.com/compile_cpp11_online.php).
struct A
{
//~A() {}
};
int main()
{
A* a = new A[10];
delete a; // heap corruption when the user destructor is defined
int *b = new int[100];
delete b; // no heap corruption
};
UB is not something you can rationalise about within the scope of the language, and at least without detailed knowledge of the toolchain, optimisation level, operating system, architecture and processor.
At a guess, though: with no destructor to call, the compiler is simply not generating any code that makes your code's fault visible in the real world. Such a destructor call may be hitting the header of your dynamically allocated memory block, which doesn't exist in the single
new A
example.