Description
Reading or writing freed memory can access memory that has already been reused for another purpose.
Potential impact
- Information exposure, memory corruption, or code execution
Remediation
Do not use pointers after freeing their memory. Define ownership clearly, and use RAII smart pointers in C++.
Examples
Before
c
char *p = malloc(16);
free(p);
p[0] = 'x';
After
c
char *p = malloc(16);
if (p == NULL) { return; }
p[0] = 'x';
free(p);
Explanation:
- Before: The pointer is used to write after its memory has been freed.
- After: Complete all uses of the allocated memory before freeing it.