How a Copied Pointer Leads to Use-After-Free in C

2026-12-01来源 dev.toEnglish

In this series, we will explore memory safety bugs in C and C++ by examining concrete examples and their corresponding fixes. We begin with a "use-after-free" vulnerability in the C language.

In C, you can allocate memory using malloc and release it using free once the data is no longer needed. However, when the same data is shared across multiple parts of a program, determining exactly when it should be freed can become challenging.

For instance, consider a scenario where two pointers reference the same memory location. If one of these pointers is used to free that memory, the data at the address held by the other pointer is no longer valid. Accessing this already-freed memory region is known as a "use-after-free" error.

Please save the following code as score.c. This code intentionally contains an "invalid read" vulnerability, which we will identify and fix.

#include <stdio.h> #include <stdlib.h> int main(void) { // Allocate memory for a single integer. int *score = malloc(sizeof *score); if (score == NULL) { return EXIT_FAILURE; } *score = 42; // Copy the address, not the integer value itself. int *view = score; // Free the memory region before a subsequent read via `view`. free(score); score = NULL; // Bug: Accessing (reading) a freed memory region via a pointer. printf("Score: %d\n", *view); return EXIT_SUCCESS; } 

What the two pointers point to

int *score = malloc(sizeof *score); 

int *score declares a pointer that references an integer. Here, the * is used for type declaration; it does not involve any memory access. malloc allocates a block of memory and returns its address, which is then used to initialize score.

At the point of initialization, no value has yet been assigned to score, but its type is already determined. In this expression, sizeof *score uses that type information to calculate the size of an int. Crucially, this does not involve reading the value of score itself, nor does it access the memory location to which score points.

After verifying that the memory allocation was successful, the program writes an integer value into the allocated memory using *score = 42. The subsequent declaration, int *view = score, copies the address. At this stage, there is still only one integer in existence.

score ---> [ Integer: 42 ] <--- view 

The Effect of free

Executing free(score) releases the allocated memory. Once this call is made, neither pointer can be used to access the integer that was previously stored there.

The following line, score = NULL, assigns a new value to the pointer variable itself. Consider the difference between these two operations:

score = NULL; // Modifies the pointer variable. *score = 0; // Writes to the integer the pointer points to. Doing this after `free` is invalid! 

These examples are provided for illustrative purposes only; do not add them directly to your program.

Assigning NULL to score does not change the value of view. Consequently, attempting to evaluate *view (for instance, in a printf statement) results in reading from memory that has already been released. Furthermore, even if you verify that view != NULL, it does not guarantee that the memory allocation remains valid (i.e., that it is still "alive"). In large-scale programs, a situation can arise where a request handler frees a buffer, yet a callback function continues to hold a pointer to that memory address. Such errors become increasingly difficult to detect when they span across different functions.

Detecting Invalid Reads

In an environment where Clang and its AddressSanitizer runtime are installed, execute the following commands:

clang -std=c11 -O0 -g -fsanitize=address score.c -o score ./score 

AddressSanitizer injects checks into the running program. When this example is executed, it reports a heap-use-after-free error, identifying where the invalid access occurred, as well as where the memory was originally allocated and subsequently freed. For further configuration details, please refer to the Clang documentation.

In a Linux test environment, adding the flags -fno-pie -no-pie to the command can prevent the program from terminating abruptly without displaying any diagnostic messages. Note that this is merely an adjustment to the build configuration; it does not fix the underlying invalid memory access.

Without such runtime checks, the program might even output 42. This occurs because memory that has been freed is not necessarily cleared immediately. However, reading from such memory constitutes "undefined behavior"—the C language specification provides no guarantees regarding the outcome.

The implications extend beyond simple program crashes. Since a memory region may still contain residual data after being freed, a "stale read" could lead to information leakage, while a "stale write" could corrupt data belonging to a different allocation. Whether a specific bug is exploitable depends on the broader context of the program and what elements an attacker might be able to influence. MITRE’s documentation on CWE-416 describes the potential consequences of such issues.

Moving the Deallocation After the Read Operation

In score.c, modify the code from the line int *view = score; through the printf statement as follows:

// Read the memory while it is still valid. int *view = score; printf("Score: %d\n", *view); // Deallocate only after the final access is complete. free(score); score = NULL; 

Recompile using the same command. This time, the program should output Score: 42 without triggering any "use-after-free" warnings.

When a callback is executed with a delay, you must determine who is responsible for ensuring (maintaining) the data's lifetime until the callback completes. Depending on your design, appropriate strategies might include waiting for the callback to finish, transferring ownership, or passing an independent copy of the data. Since testing verifies the paths that are actually executed, be sure to also examine how your code manages object lifetimes.

Kenbi

Kenbi is a static memory safety analysis tool for C and C++ that I am developing. It validates code based on ownership and lifetime rules defined through annotations. It includes an MCP (Model Context Protocol) server, allowing AI coding agents to perform checks and utilize the results to modify the code.

原文:https://www.a8q9.cn/en/article/how-a-copied-pointer-leads-to-use-after-free-in-c-80b3a1.html

相关文章