FREE.INCONSISTENT

Freeing memory inconsistent

Freeing memory inconsistently can cause a memory leak in some cases. It's important to make sure that memory is freed on all of a function's paths. The FREE.INCONSISTENT checker flags instances in which memory is accessed, either directly or through a series of dereference and field operations, and then freed on one of a function's paths but not on its other paths. Typically, this problem occurs during error conditions or when a session is unexpectedly interrupted.

Vulnerability and risk

When inconsistent memory freeing causes a memory leak, the software becomes unreliable, and if an attacker can intentionally trigger the leak, it can result in a denial-of-service (DoS) attack.

Mitigation and prevention

To avoid this problem, make sure that memory is freed on all a function's paths, including error conditions and other exceptional conditions, and that there is no confusion over which part of the program is responsible for freeing memory.

Vulnerable code example

Copy
  void my_free(char *p, int flag) {
      if (flag == 17) {
          p = 0;
          return;
      }
      if (flag == 34) {
          return;
      }
      free(p);
 }

Klocwork produces an inconsistent memory freeing report, indicating that the memory pointed by 'p' is freed at line 9, but not when the function exits at lines 4 or 7. Typically, the paths in which memory is freed are at points further removed in the code than in this example, making it difficult to recognize the situation. In any case, failing to free memory on one function path can result in a memory leak, which in turn can cause vulnerability to attack.

Extension

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