FMM.MIGHT

Freeing memory possible with mismatched function

When allocated memory is freed or deallocated, it must be done with the corresponding deallocation function. If memory 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-undefined behavior can occur. The FMM.MIGHT checker flags instances in which mismatched functions may have been used to allocate and deallocate memory.

Vulnerability and risk

Using mismatched memory allocation and deallocation functions typically results in unexpected program behavior, and can open the application to denial-of-service (DoS) attacks or memory corruption issues. Particularly in an array of objects, heap memory can be corrupted if the wrong elements of memory are freed. A significant memory leak can occur, which can be exploited as a DoS attack or a program crash.

Mitigation and prevention

Make sure you use the corresponding allocator and deallocator pairs, as shown in the following table:

Allocator Deallocator
malloc(), calloc(), realloc() free
operator new() operator delete()
operator new[]() operator delete[]()
placement new() destructor

Vulnerable code example

Copy
  class A {
          int *data;
          A(const A&) { /* prohibited */ }
          A& operator =(const A&) { /* prohibited */ }
      public:
          A() {
              data = new int [10];
          }
  
         ~A() {
             delete[] data;
         }
 };
 
 void foo(A **pp, bool t) {
     if (!*pp) {
         *pp = new A[5];
     }
     if (t) {
         delete *pp;
         *pp = 0;
     }
 }

Klocwork produces a mismatched deallocation report, indicating that the memory pointed by '*pp' was allocated through the new[] operator at line 17, and might be released by the delete operator at line 20 instead of delete[]. A mismatched set of allocator and deallocator like this can result in unpredictable program behavior, and possibly make the application vulnerable to malicious attack.

Extension

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