FNH.MIGHT

Freeing non-heap memory possible

If there is a non-heap memory deallocation-for instance, of static or stack memory-a program's memory management structures can be corrupted. The FNH.MIGHT checker flags situations in which an application might free memory that wasn't allocated using heap functions such as malloc(), calloc(), or realloc().

Vulnerability and risk

Freeing non-heap memory can cause corruption of a program's memory, resulting in program crash, and possibly creating a vulnerability that an attacker can exploit. For instance, a malicious user can use free() to access memory locations, modifying data or executing unauthorized commands or code.

Mitigation and prevention

To avoid freeing non-heap memory, make sure that you:

  • free only pointers that were allocated on the heap with malloc() previously
  • keep track of pointers and free them only once
  • free only memory that belongs to the right part of the program

Vulnerable code example

Copy
  class A {
      public:
          void foo(bool);
  };
  
  void A::foo(bool heap)
  {
      int localArray[2] = {11,22};
      int *p = localArray;
     if (heap) {
         p = new int[2];
     }
     delete[] p;
 }

Klocwork produces a non-heap memory deallocation report, indicating that 'p' might point to non-heap memory when it is passed to 'delete[]'. Freeing non-heap memory can cause an application to crash, and possibly result in vulnerability to attack.

Security training

Application security training materials provided by Secure Code Warrior.

Extension

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