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
#define TEXTURE_DATA char
#define TEXTURE_SIZE 512
class Shape {
public:
Shape() {}
~Shape() {}
void setArea(double a) { area = a; }
virtual void Draw();
private:
double area;
};
class Circle: public Shape {
public:
Circle() { texture = (TEXTURE_DATA*)malloc(TEXTURE_SIZE); }
~Circle() { free(texture); }
bool operator!=(Circle &r);
private:
TEXTURE_DATA *texture;
Circle(Circle &r) { texture = strdup(r.texture); }
Circle& operator=(Circle &r) { if (r != *this) texture = strdup(r.texture); return *this; }
};
void foo() {
Shape *newObj = new Circle;
// ... some code ...
delete newObj;
}
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
#define TEXTURE_DATA char
#define TEXTURE_SIZE 512
class Shape {
public:
Shape() {}
virtual ~Shape() {}
void setArea(double a) { area = a; }
virtual void Draw();
private:
double area;
};
class Circle: public Shape {
public:
Circle() { texture = (TEXTURE_DATA*)malloc(TEXTURE_SIZE); }
~Circle() { free(texture); }
bool operator!=(Circle &r);
private:
TEXTURE_DATA *texture;
Circle(Circle &r) { texture = strdup(r.texture); }
Circle& operator=(Circle &r) { if (r != *this) texture = strdup(r.texture); return *this; }
};
void foo() {
Shape *newObj = new Circle;
// ... some code ...
delete newObj;
}
In the fixed code, line 7 contains the virtual destructor.
Related checkers
External guidance
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.