Name: Memory is never freed

Description:

A function always returns before freeing memory that was allocated in the function. Freeing all memory allocated in the function before returning ties the lifetime of the memory blocks to that of the function call, making it easier to avoid and detect memory leaks.

ID: cpp/memory-never-freed

Kind: problem

Severity: warning

/**
 * @name Memory is never freed
 * @description A function always returns before freeing memory that was allocated in the function. Freeing all memory allocated in the function before returning ties the lifetime of the memory blocks to that of the function call, making it easier to avoid and detect memory leaks.
 * @kind problem
 * @id cpp/memory-never-freed
 * @problem.severity warning
 * @tags efficiency
 *       security
 *       external/cwe/cwe-401
 */

import MemoryFreed

from Expr alloc
where isAllocationExpr(alloc) and not allocMayBeFreed(alloc)
select alloc, "This memory is never freed"

This rule finds calls to the alloc family of functions without a corresponding free call in the entire program. This leads to memory leaks.

This check is an approximation, so some results may not be actual defects in the program. It is not possible in general to compute the exact value of the variable without running the program with all possible input data.

Recommendation

Ensure that all memory allocated by the program is freed before it terminates.

Example
     1int main(int argc, char* argv[]) {
     2    int *buff = malloc(SIZE * sizeof(int));
     3    int status = 0;
     4    ... //code that does not free buff
     5    return status; //buff is never closed
     6}
int main(int argc, char* argv[]) {
	int *buff = malloc(SIZE * sizeof(int));
	int status = 0;
	... //code that does not free buff
	return status; //buff is never closed
}