Search code examples
c++inheritancememory-leaksvirtualdestructor

Would this simple code cause a memory leak?


Say you have the following C++ code snippet:

class base {};
class derived : public base {
public:
    std::string str;
};

int main() {
    base *b = new derived();
    delete b;
}

This would leak, right? derived's string's destructor is never being called because base's destructor isn't marked as virtual. Or am I misunderstanding something?


Solution

  • You are delete-ing a derived through a pointer of type base*, and base does not have a virtual destructor.

    That is Undefined Behavior (UB), which means anything may happen.

    While causing a memory-leak if the std::string has allocated any memory (think short-string-optimization, which would mean no extra memory needs to be allocated for an empty string), is one possible (and a quite likely) manifestation of UB, that's not the worst that could happen.