CL.FMM

Freeing memory with mismatched functions

Class-level checkers produce recommendations based on Scott Meyer's rules for effective C++ class construction.

CL.FMM is based on Scott Meyer's Item 5: Use the same form in corresponding uses of new and delete. This checker looks for memory that is allocated using one mechanism and released using another; for example, mixing C and C++ memory management functions, or mixing scalar and vector memory management functions.

Vulnerability and risk

The most typical problem exposed by this checker is when memory is allocated using the C++ 'new' operator and deallocated using the C runtime function 'free()'. In this case, the C++ destructor for whatever objects may reside in that memory will not be called, so while the memory may well be deallocated, it will be done so without the programmer's intended semantic.

Also, if the different C and C++ implementations use different underlying heaps, mixing functions use can easily cause memory leaks and heap corruption.

Vulnerable code example

Copy
    class C{
      Data *data;
    public:
      C(){  data = new Data[2];}
      ~C(){  delete data;}
    };

In this example, the constructor uses the array version of operator 'new' and the destructor uses the scalar 'delete'. Even though all the memory allocated in the constructor will be released in the destructor, only one destructor of 'Data' will be called. In this case, CL.FMM has found a typical example of memory that is allocated using one mechanism ('new') and released using another ('delete').

Fixed code example

Copy
    #include <iostream>
    using namespace std;
    class Data{
    public:
      Data(){ cout << "Constructing Data at " << (void *)this << endl;}
      ~Data() {cout << "Destroying Data at " << (void *)this << endl;}
    };
//...
    int main(){
      C c;
      return 1;
    }
Output:

Constructing Data at 0x602018
Constructing Data at 0x602019
Destroying Data at 0x602019

Also, some implementations of 'new'/'delete' may cause a runtime error. To fix this problem, use the corresponding method of releasing objects:

Copy
    class C{
//...
      ~C(){  delete[] data;}
//...
    };

Extension

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