I am playing with the code
struct A {
char a[20000];
A() { a[0] = 'A'; }
~A() {}
};
struct B : A {
char a[20000];
B() { a[0] = 'B'; }
~B() {}
};
int main() {
A *pA = new A;
A *pB = new B;
delete pA;
delete pB;
return 0;
}
Some people wrote (why do we need a virtual destructor with dynamic memory?) that it should cause a memory leak but it doesn't. I used g++, then valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt and get
HEAP SUMMARY:
in use at exit: 0 bytes in 0 blocks
total heap usage: 3 allocs, 3 frees, 132,704 bytes allocated
All heap blocks were freed -- no leaks are possible
I know that some old compilers had problems when they try to free memory in similar situations but it looks like that the modern C++ can free memory seamlessly in this case. So I am curios how is it possible? Maybe delete uses information provided by OS for a given allocated memory block?
EDIT. It is still unclear for me what exactly can cause the UB for delete *pB if we have empty destructors and constructors. An answer for a question (Missing Virtual Destructor Memory Effects) shows that there are no any UB.