Freed Pointer Passed to String Functions
String manipulation functions receiving pointers that have already been freed, leading to use-after-free vulnerabilities.
A critical memory safety vulnerability where C/C++ code passes previously freed pointers to functions, creating use-after-free conditions that can enable memory corruption, crashes, data corruption, or remote code execution. When an attacker can influence heap layout and reuse the freed memory, they may be able to control program execution flow or corrupt critical data structures, leading to arbitrary code execution or privilege escalation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char* data;
struct node* next;
} node_t;
// VULNERABLE: Use-after-free when removing node
void remove_node(node_t** head, const char* data) {
node_t* current = *head;
node_t* prev = NULL;
while (current) {
if (strcmp(current->data, data) == 0) {
free(current->data);
free(current);
if (prev) {
prev->next = current->next; // USE-AFTER-FREE!
} else {
*head = current->next; // USE-AFTER-FREE!
}
return;
}
prev = current;
current = current->next;
}
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
char* data;
struct node* next;
} node_t;
// SECURE: Save next pointer before freeing
void remove_node(node_t** head, const char* data) {
node_t* current = *head;
node_t* prev = NULL;
while (current) {
if (strcmp(current->data, data) == 0) {
node_t* next = current->next; // Save before free
free(current->data);
free(current);
if (prev) {
prev->next = next; // Use saved pointer
} else {
*head = next; // Use saved pointer
}
return;
}
prev = current;
current = current->next;
}
}The vulnerable code frees the node and then accesses current->next, which is use-after-free. The secure version saves the next pointer before freeing the node, preventing access to freed memory.
String manipulation functions receiving pointers that have already been freed, leading to use-after-free vulnerabilities.
Sourcery automatically identifies remote code execution from passing freed pointer to function and many other security issues in your codebase.