CL.FMMFreeing memory with mismatched functionsClass-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 riskThe 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 example1 class C{ 2 Data *data; 3 public: 4 C(){ data = new Data[2];} 5 ~C(){ delete data;} 6 }; 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 example1 #include <iostream> 2 using namespace std; 3 class Data{ 4 public: 5 Data(){ cout << "Constructing Data at " << (void *)this << endl;} 6 ~Data() {cout << "Destroying Data at " << (void *)this << endl;} 7 }; //... 8 int main(){ 9 C c; 10 return 1; 11 } 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: 1 class C{ //... 2 ~C(){ delete[] data;} //... 3 }; Related checkersExternal guidanceExtensionThis checker can be extended through the Klocwork knowledge base. See Tuning C/C++ analysis for more information. |