CWARN.DTOR.NONVIRT.NOTEMPTYInherited virtual functions in class but destructor is not virtual and not emptyThe CWARN.DTOR.NONVIRT.NOTEMPTY checker flags classes in which the class declares virtual member functions inherited from its base class, but its destructor isn't virtual or empty. Vulnerability and riskWhen an object of a class derived from a base class is deleted through a pointer to the base class, the destructor of the derived class isn't executed, and members of the derived class aren't disposed of correctly. This situation can lead to leaked memory and unreleased resources. Mitigation and preventionIt's important to provide a virtual destructor, even if it will be empty, in a class that contains a virtual method and some member data that must be properly disposed of, implicitly or explicitly. Derived classes will inherit from the base class, and if the base class destructor isn't defined as virtual, memory won't be deallocated properly. In a hierarchy of classes declaring or overriding virtual functions, the virtual destructor has to be defined only once, for the root class of the hierarchy. Vulnerable code example1 #include <iostream> 2 using namespace std; 3 4 class A 5 { 6 public: 7 8 ~A() {std::cout << "I am A" << std::endl;} 9 virtual void f1(); 10 }; 11 12 class B : public A 13 { 14 public: 15 16 ~B() {cout << "I am B" << endl;} 17 virtual void f1(); 18 }; In this code example, the non-virtual destructor in class A means that Klocwork flags line 16. Related checkers |