Start here

Home
About Klocwork
What's new
Fixed issues
Release notes
Installation

Reference

C/C++ checkers
Java checkers
C# checkers
MISRA C 2004 checkers
MISRA C++ 2008 checkers
MISRA C 2012 checkers
MISRA C 2012 checkers with Amendment 1
Commands
Metrics
Troubleshooting
Reference

Product components

C/C++ Integration build analysis
Java Integration build analysis
Desktop analysis
Refactoring
Klocwork Static Code Analysis
Klocwork Code Review
Structure101
Tuning
Custom checkers

Coding environments

Visual Studio
Eclipse for C/C++
Eclipse for Java
IntelliJ IDEA
Other

Administration

Project configuration
Build configuration
Administration
Analysis performance
Server performance
Security/permissions
Licensing
Klocwork Static Code Analysis Web API
Klocwork Code Review Web API

Community

View help online
Visit RogueWave.com
Klocwork Support
Rogue Wave Videos

Legal

Legal information

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

1    class C{
2      char *data;
3    public:
4      C(){ data = new char[10]; }
//...
5    };

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:

1    void foo(){
2      C c;
3    }

Fixed code example

1    class C{
//...
2      ~C() { delete[] data;}
//...
3    };

In the fixed code, a destructor releases the allocated memory.

Extension

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