CL.MLK.VIRTUAL

Virtual memory leak

This is a class-level (CL) checker that notifies the user of the potential for a memory leak. CL.MLK.VIRTUAL is reported when the class contains at least one virtual method (implying that it is intended to act as a base class for inheritance), the destructor of a derived class performs memory deallocation, but the base class destructor is not declared virtual. In this case, should a program destroy a pointer to an up-cast base type for an object of a derived type, the destructor for the derived type will not be called.

Vulnerability and risk

In such a case, dynamic memory associated with a derived type will not be destroyed correctly; that is, any required destructors will not be invoked, resulting in unexpected program behavior.

Vulnerable code example

1    #define TEXTURE_DATA char
2    #define TEXTURE_SIZE 512
3 
4       class Shape {
5    public:
6       Shape() {}
7       ~Shape() {}
8       void setArea(double a) { area = a; }
9       virtual void Draw();
10   private:
11      double area;
12   };
13 
14   class Circle: public Shape {
15   public:
16      Circle() { texture = (TEXTURE_DATA*)malloc(TEXTURE_SIZE); }
17      ~Circle() { free(texture); }
18      bool operator!=(Circle &r);
19   private:
20      TEXTURE_DATA *texture;
21      Circle(Circle &r) { texture = strdup(r.texture); }
22      Circle& operator=(Circle &r) { if (r != *this) texture = strdup(r.texture); return *this; }
23   };
24 
25   void foo() {
26      Shape *newObj = new Circle;
27      // ... some code ...
28      delete newObj;
29   }

The memory referenced by 'texture' may be not deallocated in the destructor. The destructor on the base class 'Shape' is not defined as virtual, and so when deleting through the up-cast base class, the derived class's destructor will not be invoked, resulting in a memory leak.

Fixed code example

1   #define TEXTURE_DATA char
2   #define TEXTURE_SIZE 512
3 
4   class Shape {
5   public:
6       Shape() {}
7       virtual ~Shape() {}
8       void setArea(double a) { area = a; }
9       virtual void Draw();
10  private:
11  double area;
12  };
13 
14  class Circle: public Shape {
15  public:
16      Circle() { texture = (TEXTURE_DATA*)malloc(TEXTURE_SIZE); }
17      ~Circle() { free(texture); }
18      bool operator!=(Circle &r);
19  private:
20      TEXTURE_DATA *texture;
21      Circle(Circle &r) { texture = strdup(r.texture); }
22      Circle& operator=(Circle &r) { if (r != *this) texture = strdup(r.texture); return *this; }
23  };
24 
25  void foo() {
26      Shape *newObj = new Circle;
27      // ... some code ...
28      delete newObj;
29  }

In the fixed code, line 7 contains the virtual destructor.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.