CWARN.DTOR.NONVIRT.DELETE

Delete expression of a class with virtual methods and no virtual destructor

The CWARN.DTR.NONVIRT.DELETE checker finds deletions of objects in classes that have virtual methods but no virtual destructor.

Vulnerability and risk

When 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 prevention

It'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 example

Copy
   class A
   {
   public:
    
       ~A() {cout << "I am A" << endl;}
       virtual void f1();
   };
    
   class B : public A
  {
  public:
   
      virtual ~B() {cout << "I am B" << endl;}
      virtual void f1();
  };
   
  void foo() {
      A *a = new B;
      delete a; 
  }

In this code example, the lack of a virtual destructor in class A means that Klocwork flags the deletion at line 19.