CL.MLK
Memory leak in destructor
This is a class-level (CL) checker that notifies you of a potential for a memory leak in the class. Class-level checkers produce recommendations based on Scott Meyer's rules for effective C++ class construction.
CL.MLK is based on Scott Meyer's Item 6: Use delete on pointer members in destructors. Klocwork reports CL.MLK when a class performing dynamic memory allocation in the constructor doesn't release that memory in the destructor, leading to a possible memory leak.
Vulnerability and risk
Memory leaks cause the application to consume additional memory. This reduces the amount of memory available to other applications and eventually causes the operating system to start paging, slowing the system down. In critical cases, the application will reach overall memory limits, which may result in application crashes.
Vulnerable code example
class C{
char *data;
public:
C(){ data = new char[10]; }
//...
};
In this example, class 'C' allocates memory in the constructor, but it doesn't have a destructor. CL.MLK has found a class performing dynamic memory allocation in the constructor, which doesn't release that memory in the destructor, leading to a possible memory leak. Even if there are methods other than a destructor that release the allocated memory, it is still possible to use the class so that there will be a memory leak.
Even a simple declaration of an unused object will lead to a memory leak:
void foo(){
C c;
}
Fixed code example
class C{
//...
~C() { delete[] data;}
//...
};
In the fixed code, a destructor releases the allocated memory.
Related checkers
External guidance
Extension
This checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information.