Juha Nieminen wrote:
Sam wrote:
Generally, an attempt to destroy a superclass, without a virtual
destructor present, is undefined behavior. Practically, it results in
leaked memory, and memory corruption.
Why would destroying an object of derived type using a base type
pointer, in the case where this base type has no virtual destructor,
result in a memory leak and memory corruption (assuming, like was the
case here, that the derived class only has an array as member)?
Sure, the derived destructor will not be called,
That's one possibility, but formally, the behavior is undefined.
but in this case, why
would that cause any leaks or corruption? It's not like the memory
manager would only free part of the allocated memory block (at least if
a regular compiler-provided default allocator is used).
In general, it's pointless to speculate about what might be the cause
of various things when code has undefined behavior. One reason for
making it undefined is that there are may things that can go wrong.
For example, usually the destructor frees the memory. The destructor
knows the object's type and how large it is; there's nothing
prohibiting taking advantage of that knowledge. Further, if the
underlying memory manager is malloc/free, it won't work right if the
address of the base sub-object is different from the address of the
actual type.