A program may allocate an additional memory block using the malloc
function. When no longer needed, such memory blocks are released
using the free
function. After it is released, reading or writing to a heap-allocated memory block leads to undefined behavior.
char *cp = (char*)malloc(sizeof(char)*10); // memory is allocated
// all bytes in cp can be used here
free(cp); // memory is released
cp[9] = 0; // Noncompliant: memory is used after it was released
In addition to the malloc
and free
pair, in C++ a heap memory may be acquired by use of the operator new
,
and later released using the operator delete
.
int *intArray = new int[20]; // memory is allocated
// elements of intArray can be written or read here
delete[] intArray; // memory is released
intArray[3] = 10; // Noncompliant: memory is used after it was released
Releasing a memory block by invoking free
or operator delete
informs the memory management system that the program no
longer uses the given block. Depending on the state and load of the program, such block can be then:
- reused, i.e., the allocation function returns the same pointer,
- released to the operating system, making it inaccessible to the program.
What is the potential impact?
Accessing released memory causes undefined behavior. This means the compiler is not bound by the language standard anymore, and your program has no
meaning assigned to it.
Practically this has a wide range of effects:
- The program may crash due to the memory no longer being accessible, or due to unexpected value being read or written via the pointer.
- Reading from the released memory may produce a garbage value.
- When the memory was already reused to store sensitive data, such as passwords, it may lead to a vulnerability that uses this defect to extract
information from an instance of the program.
- Writing to released memory may change the value of the unrelated object in a remote part of the code if the memory was reused by it. As
different objects may reuse same the block of memory between runs, this leads to unintuitive and hard diagnose bugs.