Use of previously freed memory
ID |
c.memory_management.use_after_free |
Severity |
high |
Remediation Complexity |
hard |
Remediation Risk |
high |
Remediation Effort |
medium |
Resource |
Memory Management |
Language |
C / C++ |
Description
The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system’s reuse of the freed memory.
Rationale
The use of previously-freed memory can have any number of adverse consequences, ranging from the corruption of valid data to the execution of arbitrary code, depending on the instantiation and timing of the flaw. The simplest way data corruption may occur involves the system’s reuse of the freed memory.
The following code illustrates a vulnerable pattern detected by this rule:
void alloc_and_free1()
{
int err = 1, bailout = 0;
char *ptr = (char *)malloc(MEMSIZE);
// this should be caught but it isn't, due to a documented limitation in semgrep
// https://semgrep.dev/docs/writing-rules/pattern-syntax/#ellipses-and-statement-blocks
if (err)
{
bailout = 1;
free(ptr);
}
if (bailout)
fprintf(stderr, "error: %p\n", ptr);
free(ptr);
// VULNERABLE: Use of previously freed memory
fprintf(stderr, "error: %p\n", ptr);
}