How to Fix C++ Missing Virtual Destructor Memory Leaks
In this tutorial, you'll learn about How to Fix C++ Missing Virtual Destructor Memory Leaks. We cover key concepts, practical examples, and best practices.
C++ undefined behavior occurs when a derived class object is deleted through a base class pointer without a virtual destructor. Only the base destructor runs, and derived resources are leaked.
Quick Fix
Wrong
struct Base {
~Base() {} // non-virtual
};
struct Derived : Base {
int* data = new int[100];
~Derived() { delete[] data; }
};
int main() {
Base* obj = new Derived();
delete obj; // only Base::~Base() is called!
}
Derived::~Derived() is never called, leaking the data array.
Right
struct Base {
virtual ~Base() = default;
};
struct Derived : Base {
int* data = new int[100];
~Derived() override { delete[] data; }
};
int main() {
Base* obj = new Derived();
delete obj; // both ~Derived() and ~Base() are called
}
Fix for abstract classes
struct Interface {
virtual void doSomething() = 0;
virtual ~Interface() = default;
};
Fix for polymorphic deletion
struct Base {
virtual ~Base() = default;
virtual void foo() {}
};
Fix without RTTI
template <typename T>
void safeDelete(T*& ptr) {
static_assert(std::has_virtual_destructor_v<T>,
"Type must have virtual destructor");
delete ptr;
ptr = nullptr;
}
Prevention
- Always declare destructors as
virtualin base classes. - Use
overridekeyword to catch missing virtual base destructors. - Use
std::unique_ptr<Base>which correctly calls the derived destructor if Base has a virtual destructor. - Mark base classes with
virtual ~Base() = default. - Enable compiler warnings:
-Wdelete-non-virtual-dtorin GCC/Clang.
DodaTech Tools
Doda Browser's C++ class hierarchy inspector flags missing virtual destructors in polymorphic classes. DodaZIP archives heap profiles for leak detection. Durga Antivirus Pro detects memory corruption from incorrect polymorphic deletion.
Common Mistakes with virtual destructor
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world CPP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro