Freeing Memory But Continuing to Use Pointer
Calling free() on a pointer but continuing to dereference it afterwards without reallocating.
Use-after-free vulnerabilities occur when code dereferences a pointer after the memory it points to has been freed. This can enable memory corruption, crashes, data corruption, or remote code execution when freed memory is reallocated and controlled by an attacker. The dangling pointer may point to reclaimed memory containing attacker-controlled data.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// VULNERABLE: Use-after-free
void process_data() {
char* buffer = malloc(100);
if (buffer == NULL) return;
strcpy(buffer, "Hello");
free(buffer);
// USE-AFTER-FREE!
printf("%s\n", buffer);
strcpy(buffer, "Bad");
}#include <stdlib.h>
#include <string.h>
#include <stdio.h>
// SECURE: Proper pointer management
void process_data() {
char* buffer = malloc(100);
if (buffer == NULL) return;
strcpy(buffer, "Hello");
// Use before freeing
printf("%s\n", buffer);
free(buffer);
buffer = NULL; // Prevent reuse
// Safe: won't execute
if (buffer != NULL) {
strcpy(buffer, "Won't execute");
}
}The vulnerable code dereferences buffer after calling free(), causing use-after-free. The secure version uses the buffer before freeing it and sets the pointer to NULL afterwards to prevent accidental reuse.
Calling free() on a pointer but continuing to dereference it afterwards without reallocating.
Sourcery automatically identifies memory corruption due to use-after-free pointer dereference and many other security issues in your codebase.