FNH.MUST

Freeing non-heap memory

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.MUST checker flags situations in which an application frees 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();
  };
  
  void A::foo()
  {
      int localArray[2] = { 11, 22 };
      delete[] localArray;
 }

Klocwork produces a non-heap memory deallocation report, indicating that 'localArray' points to a 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.