Invalid free

Freeing memory that was not dynamically allocated

Description

Passing memory that was not dynamically allocated, a stack variable, or the address of a local object whose lifetime has ended to free, delete, or a kernel pool release function can cause invalid memory deallocation.

Potential impact

  • Process crashes or kernel panics can cause denial of service.
  • Corrupted heap metadata can lead to unpredictable behavior or security vulnerabilities.

Remediation

  1. Use free for memory allocated by the malloc, calloc, or realloc family.
  2. Use delete only for objects allocated with new.
  3. Do not pass addresses of stack or global variables to deallocation functions.

Examples

Before

c
void run(void) {
    int value = 0;
    int *p = &value;
    free(p);
}

After

c
void run(void) {
    int *p = malloc(sizeof(int));
    if (p == NULL) {
        return;
    }
    free(p);
}

Explanation:

  • Before: p points to the stack variable value, so free(p) is invalid.
  • After: p points to heap memory allocated with malloc and is released with the matching free function.

References