Programming Search⌘K

Weaknesscore

Use after free

Also called UAF, dangling pointer, cwe-416.

A use after free happens when a program uses a pointer to memory that it has already freed, so it reads or writes memory that may now belong to a different object.

Abstraction
variant
CWE Top 25 (2025)
rank 7
Languages affected
c, cpp, unsafe-code-in-any-language

Description

In C and C++, a program asks the allocator for a block of memory, uses it through pointers, and gives it back with free or delete. The free returns the block to the allocator. It does not change the pointers that still hold its address. A use after free happens when the program later reads or writes through one of those pointers.1 The pointer is now dangling. The allocator can give the same block to a new object, and the old pointer then points into that new object.1 The program meant to read a session. It reads whatever lives there now.

The root cause is that the lifetime of an object is not part of its pointer. Nothing in the type of a pointer says if the memory is still valid. The rule "who frees this, and when" lives in comments and in the heads of developers. It breaks when two parts of a program keep pointers to the same object, when an error path frees early, when a callback runs after the owner is gone, and when a container moves its elements. CWE-416 says that a use after free is resultant: some other error came first, such as a race condition, a badly handled error, confusion over which part of the program frees the memory, or a free that is too early.1

The effects depend on what the block holds when the old pointer is used. A read can leak data of another object, and a write can corrupt it. If the new object holds function pointers, as C++ objects with virtual functions do, a write through the old pointer can lead to code execution.1 Afek and Sharabani showed in 2007 that an attacker who controls the new contents of the block can change the behavior of the program.4 OWASP describes the same pattern in a browser: script makes the browser free an object while a dangling pointer to it remains, and then makes a new object in the same memory.3

CWE-416 names this weakness. Its alternate terms are dangling pointer, UAF and use-after-free. It is a variant weakness under CWE-825, expired pointer dereference, and a peer of the double free, CWE-415.1 CWE-416 lists C and C++ as languages where it is often prevalent. It is rank 7 of the 2025 CWE Top 25, with 14 CVEs in the CISA catalogue of known exploited vulnerabilities. Only OS command injection has more on that list.2 The OWASP Top 10:2025 maps it to X02:2025 Memory Management Failures, a category in its Next Steps section and not in the ten.3 The Chromium project finds that around 70% of its high severity security bugs are memory unsafety problems, and that half of those are use-after-free bugs.7

History

In 2007, Jonathan Afek and Adi Sharabani of Watchfire published the whitepaper "Dangling Pointer: Smashing the Pointer for Fun and Profit".4 It said that many developers called the dangling pointer a quality problem, and that security experts did not consider it a severe issue. It said that no exploit of this type of bug was publicly known, and it presented one against Microsoft IIS 5.1.4 In January 2010, CVE-2010-0249 recorded a use after free in Internet Explorer that had been exploited in the wild in December 2009 and January 2010, during Operation Aurora.5

Vulnerable code

close_session frees the session, and main then reads it through the old pointer. The block builds with AddressSanitizer, which reports the read.6

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

struct session {
    char user[16];
    int logged_in;
};

struct session *open_session(const char *user) {
    struct session *s = calloc(1, sizeof *s);
    if (s != NULL) {
        snprintf(s->user, sizeof s->user, "%s", user);
        s->logged_in = 1;
    }
    return s;
}

void close_session(struct session *s) {
    free(s);
}

int main(void) {
    struct session *s = open_session("alice");
    if (s == NULL) {
        return 1;
    }
    close_session(s);
    printf("%s logged in: %d\n", s->user, s->logged_in); // s points to freed memory
}

AddressSanitizer stops the program with a heap-use-after-free report. Without the sanitizer, the behavior is undefined. The program may print the old values, other data or garbage, and still exit with status 0. Nothing in the output says that the read was wrong.

A use after free does not need a visible free. In C++, push_back on a full vector allocates a new block, moves the elements and frees the old block. The standard says that the reallocation invalidates all references, pointers and iterators to the elements.8 A reference taken before the call then dangles. The C++ example file shows AddressSanitizer catching it.

Fixed code

The program uses the session before it closes it, and close_session clears the pointer of the caller. The block builds with AddressSanitizer and UndefinedBehaviorSanitizer, and both stay silent.

#include <stdio.h>
#include <stdlib.h>

struct session {
    char user[16];
    int logged_in;
};

struct session *open_session(const char *user) {
    struct session *s = calloc(1, sizeof *s);
    if (s != NULL) {
        snprintf(s->user, sizeof s->user, "%s", user);
        s->logged_in = 1;
    }
    return s;
}

// Frees the session and clears the pointer of the caller.
void close_session(struct session **s) {
    free(*s);
    *s = NULL;
}

int main(void) {
    struct session *s = open_session("alice");
    if (s == NULL) {
        return 1;
    }
    printf("%s logged in: %d\n", s->user, s->logged_in);
    close_session(&s);
    if (s == NULL) {
        printf("the session is closed\n");
    }
}
Output
alice logged in: 1
the session is closed

The order of the calls is the fix. Setting the pointer to NULL is defence in depth. CWE-416 says that a later use then becomes a null pointer dereference, which can still crash but reduces or removes the risk of code execution. It also warns that complex data structures make this measure less useful, because other copies of the pointer keep the old address.1

Ownership checked by the compiler

Rust makes each value have one owner and checks every reference against the lifetime of its value. The program below frees the string with drop while a reference to it is still in use.

This code does not compile, on purpose. The error is E0505.

fn main() {
    let session = String::from("alice");
    let user = &session;
    drop(session);
    println!("{user}");
}
Error output
error[E0505]: cannot move out of `session` because it is borrowed
 --> main.rs:4:10
  |
2 |     let session = String::from("alice");
  |         ------- binding `session` declared here
3 |     let user = &session;
  |                -------- borrow of `session` occurs here
4 |     drop(session);
  |          ^^^^^^^ move out of `session` occurs here
5 |     println!("{user}");
  |                ---- borrow later used here
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let user = &session.clone();
  |                        ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0505`.

The compiler rejects the program. The Rust book says that the compiler guarantees that references will never be dangling: the data will not go out of scope before the reference to it does.9 The Rust example file also shows the vector case from C++, which fails with error E0502.

Garbage collection

Go, Java, C#, Python and JavaScript free an object only when no reference to it is left, so code in these languages cannot reach freed memory. OWASP lists them as memory-safe.3 The Go FAQ says that each variable exists as long as there are references to it, and that the compiler moves a local variable to the heap when it cannot prove that the variable is not used after the function returns.10

The same mistake still happens one level up, with resources that the program closes by hand. Here it is safe and visible. Python raises ValueError for an operation on a closed file.11 Java throws IOException for a read from a closed reader.12 .NET throws ObjectDisposedException for a member of a disposed object.13 The C# documentation says to declare a disposable variable in the using statement, because an instance that stays in scope after the dispose can still be used.14 The example files show each case.

How to detect it

  • Sanitizers. Build the tests with -fsanitize=address. AddressSanitizer detects use after free, use after return, use after scope and double free.6 It finds the bug only when a test runs the path, so combine it with fuzzing.3
  • Static analysis. CodeQL query cpp/use-after-free finds accesses through a pointer after the memory is freed. Its documentation says that the check is an approximation.15 OWASP lists code reviews and static analysis.3
  • Code review. For each free, delete and close, find every other pointer to the object and check that no code uses it after that point. Look at error paths, callbacks, destructors and code that runs on two threads. Two of the real cases below start with a race condition.1718 For each reference into a container, check that no call between its creation and its use can change the container.

How to prevent it

  • Use a memory-safe language. CWE-416 lists a language with automatic memory management as its first mitigation. OWASP puts a memory-safe language first among its defences against memory management failures.13
  • Give each object one owner. Decide which part of the program frees each object, and let no other part free it. CWE-416 names confusion over this as one cause of the weakness.1 In Rust, the compiler checks ownership.9
  • Do not keep references across a change. Keep an index or a copy across a call that can reallocate or remove elements of a container.8
  • Clear the pointer after the free. It turns a later use into a null pointer dereference. It is defence in depth, not a fix.1
  • Limit the scope of resources. Use with in Python, try-with-resources in Java and using in C#, so that the name of a closed resource is not in scope after the close.14

Real cases

Case Date What happened
CVE-2010-0249 published 2010-01-15 A use after free in Internet Explorer 6, 7 and 8 let remote attackers run code through a pointer to a deleted object. It was exploited in the wild during Operation Aurora.5
CVE-2014-1776 published 2014-04-27 A use after free in Internet Explorer 6 through 11, related to CMarkup::IsConnectedToPrimaryMarkup, let remote attackers run code. It was exploited in the wild in April 2014.16
CVE-2020-6819 published 2020-04-24 A race condition in the nsDocShell destructor of Firefox could cause a use after free. Mozilla was aware of targeted attacks in the wild.17
CVE-2021-0920 published 2021-12-15 A race condition in unix_scm_to_skb of af_unix.c in the kernel used by Android caused a use after free and could lead to local escalation of privilege.181
PythonGitHub

This code raises ValueError, on purpose.

import io

f = io.StringIO("alice\nbob\n")
print(f.readline(), end="")
f.close()
print(f.readline(), end="")
import io

with io.StringIO("alice\nbob\n") as f:
    for line in f:
        print(line, end="")
print("closed:", f.closed)
Output
alice
bob
closed: True
  • Verdict: native. Python frees an object only when no reference to it is left, so Python code cannot reach freed memory. OWASP lists Python among the memory-safe languages.
  • The bug moves to resources. The documentation of close says that once the file is closed, any operation on it raises ValueError. The error is safe and visible.
  • A with block closes the file at its end. The name f still exists after the block, so a later use is possible, but it fails with the error.
  • C extensions and ctypes manage memory by hand, and a bug in them is a use after free in the interpreter process.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"alice"};
    const std::string& first = names[0];
    names.push_back("bob"); // the vector moves its elements to a new block
    std::println("first: {}", first);
}

AddressSanitizer reports a heap-use-after-free. There is no delete in the program. The vector had room for one element, so push_back allocated a new block, moved the elements and freed the old block. The reference first still points into the old block.

#include <cstddef>
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"alice"};
    std::size_t first = 0; // an index stays valid when the vector grows
    names.push_back("bob");
    std::println("first: {}", names[first]);
}
Output
first: alice
  • Verdict: library. The standard says that a reallocation of a vector invalidates all references, pointers and iterators to its elements. Other containers and operations have their own rules, and the compiler does not check them.
  • Keep an index or a copy, not a reference, across a call that can change the container.
  • std::unique_ptr gives each object one owner and frees it once. std::shared_ptr keeps an object alive while any owner exists, and std::weak_ptr lets code check that the object still exists before it uses it.
  • A raw pointer or a reference that outlives its object is the same bug as in C. AddressSanitizer finds it when a test runs the path.
JavaGitHub

This code raises IOException, on purpose.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new StringReader("alice\nbob\n"));
        System.out.println(reader.readLine());
        reader.close();
        System.out.println(reader.readLine());
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(new StringReader("alice\nbob\n"))) {
            System.out.println(reader.readLine());
            System.out.println(reader.readLine());
        }
        // reader is not in scope here, so no code can use it after the close.
    }
}
Output
alice
bob
  • Verdict: native. The garbage collector keeps each object alive while a reference to it exists, so Java code cannot use freed memory.
  • The bug moves to resources. The documentation of Reader.close says that after the close, further calls to read and some other methods throw IOException. The error is safe and visible.
  • try-with-resources closes the resource at the end of the block, and the variable is not in scope after it.
  • Native code through JNI can free memory that Java still points to. Such code has the same weakness as C.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>
#include <stdlib.h>

struct session {
    char user[16];
    int logged_in;
};

struct session *open_session(const char *user) {
    struct session *s = calloc(1, sizeof *s);
    if (s != NULL) {
        snprintf(s->user, sizeof s->user, "%s", user);
        s->logged_in = 1;
    }
    return s;
}

void close_session(struct session *s) {
    free(s);
}

int main(void) {
    struct session *s = open_session("alice");
    if (s == NULL) {
        return 1;
    }
    close_session(s);
    printf("%s logged in: %d\n", s->user, s->logged_in); // s points to freed memory
}

AddressSanitizer reports a heap-use-after-free on the read in main. Without the sanitizer, the program can print the old values, because free does not clear the memory. It can also print values of a new object that reuses the block.

#include <stdio.h>
#include <stdlib.h>

struct session {
    char user[16];
    int logged_in;
};

struct session *open_session(const char *user) {
    struct session *s = calloc(1, sizeof *s);
    if (s != NULL) {
        snprintf(s->user, sizeof s->user, "%s", user);
        s->logged_in = 1;
    }
    return s;
}

// Frees the session and clears the pointer of the caller.
void close_session(struct session **s) {
    free(*s);
    *s = NULL;
}

int main(void) {
    struct session *s = open_session("alice");
    if (s == NULL) {
        return 1;
    }
    printf("%s logged in: %d\n", s->user, s->logged_in);
    close_session(&s);
    if (s == NULL) {
        printf("the session is closed\n");
    }
}
Output
alice logged in: 1
the session is closed
  • Verdict: absent. C has no ownership or lifetime rules in the language. After free, each copy of the pointer is dangling, and nothing marks it.
  • close_session takes the address of the pointer and sets it to NULL. CWE-416 lists this as defence in depth: a later use is then a null pointer dereference, which crashes instead of reading reused memory. It does not clear other copies of the pointer.
  • The real fix is a rule for each object: one owner frees it, and no other code keeps a pointer past that point. Write the rule down in the comment of each function that takes or returns a pointer.
  • Build tests with -fsanitize=address. It also reports a double free, a peer weakness, CWE-415.

This code raises ObjectDisposedException, on purpose.

using System.Text;

var stream = new MemoryStream();
stream.Write(Encoding.UTF8.GetBytes("alice\n"));
stream.Dispose();
stream.Write(Encoding.UTF8.GetBytes("bob\n"));
using System.Text;

static void WriteSession()
{
    using var stream = new MemoryStream();
    stream.Write(Encoding.UTF8.GetBytes("alice\n"));
    Console.WriteLine($"wrote {stream.Length} bytes");
} // stream is disposed here, and its name is out of scope

WriteSession();
Output
wrote 6 bytes
  • Verdict: native. The garbage collector frees an object only when no reference to it is left, so safe C# code cannot use freed memory.
  • The bug moves to resources that implement IDisposable. An operation on a disposed object throws ObjectDisposedException.
  • The C# documentation says to declare a disposable variable in the using statement or with a using declaration, because an instance that stays in scope after it is disposed can still be used.
  • unsafe code with pointers, Marshal.FreeHGlobal and native code through P/Invoke manage memory by hand and have the same weakness as C.
package main

import "fmt"

type session struct {
	user     string
	loggedIn bool
}

// openSession returns the address of a local variable.
func openSession(user string) *session {
	s := session{user: user, loggedIn: true}
	return &s
}

func main() {
	s := openSession("alice")
	fmt.Println(s.user, "logged in:", s.loggedIn)
}
Output
alice logged in: true

In C, this function would return a dangling pointer to its stack frame. In Go, each variable exists as long as there are references to it. When the compiler cannot prove that a local variable is not used after the function returns, it puts the variable on the garbage-collected heap.

This code runs but gives a wrong answer on purpose.

package main

import (
	"errors"
	"fmt"
	"os"
)

func main() {
	f, err := os.CreateTemp("", "session")
	if err != nil {
		panic(err)
	}
	defer os.Remove(f.Name())
	f.Close()

	_, err = f.WriteString("alice\n")
	fmt.Println("write after close:", err != nil, errors.Is(err, os.ErrClosed))
}
Output
write after close: true true
  • Verdict: native. The garbage collector frees memory only when no reference to it is left, so a pointer cannot point to freed memory.
  • The same mistake still happens with resources that the program closes by hand: files, connections, buffers from a pool. The memory is safe, and the operation returns an error such as os.ErrClosed. Check the error, and use defer f.Close() after a successful open so the close happens at the end of the function.
  • The packages unsafe and cgo can hold pointers that the collector does not track. Memory that C code frees can still be used from Go.
RustGitHub

This code does not compile, on purpose. The error is E0502.

fn main() {
    let mut names = vec![String::from("alice")];
    let first = &names[0];
    names.push(String::from("bob"));
    println!("first: {first}");
}
Error output
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
 --> main.rs:4:5
  |
3 |     let first = &names[0];
  |                  ----- immutable borrow occurs here
4 |     names.push(String::from("bob"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("first: {first}");
  |                       ----- immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.

This is the C++ bug from the C++ example file. The compiler rejects it. push needs a mutable borrow of names, and the shared borrow first is still live.

This code does not compile, on purpose. The error is E0505.

fn main() {
    let session = String::from("alice");
    let user = &session;
    drop(session);
    println!("{user}");
}
Error output
error[E0505]: cannot move out of `session` because it is borrowed
 --> main.rs:4:10
  |
2 |     let session = String::from("alice");
  |         ------- binding `session` declared here
3 |     let user = &session;
  |                -------- borrow of `session` occurs here
4 |     drop(session);
  |          ^^^^^^^ move out of `session` occurs here
5 |     println!("{user}");
  |                ---- borrow later used here
  |
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let user = &session.clone();
  |                        ++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0505`.

drop frees the string. The compiler rejects the move into drop, because the borrow user is used after it.

fn main() {
    let mut names = vec![String::from("alice")];
    let first = 0;
    names.push(String::from("bob"));
    println!("first: {}", names[first]);
}
Output
first: alice
  • Verdict: native. The borrow checker proves at compile time that no reference outlives the value it points to. The Rust book says that the compiler guarantees that references will never be dangling.
  • Each value has one owner, and the value is freed when the owner goes out of scope, once. A moved value cannot be used again.
  • Rc and Arc share ownership, and Weak gives a reference that must be upgraded and checked before use.
  • unsafe code with raw pointers can still use freed memory. Keep it small, and review each raw pointer for the lifetime of its target.

References

  1. CWE-416: Use After Free, Description; Alternate Terms; Common Consequences; Potential Mitigations; Relationships; Weakness Ordinalities; Observed Examples
  2. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 7, CVEs in KEV
  3. OWASP Top 10:2025, Next Steps, X02:2025 Memory Management Failures, X02:2025, Description; How to prevent; Example attack scenarios; List of Mapped CWEs
  4. Jonathan Afek and Adi Sharabani, Dangling Pointer: Smashing the Pointer for Fun and Profit, Watchfire, 2007, 1. Abstract; 2. Understanding the Dangling Pointer Bug
  5. CVE-2010-0249, Microsoft Internet Explorer, the description and the publication date
  6. Clang documentation, AddressSanitizer, Introduction; Usage
  7. The Chromium Projects, Memory safety, the opening statistics
  8. Working Draft, Programming Languages: C++, [vector.modifiers], Remarks on insert, emplace_back and push_back
  9. The Rust Programming Language, References and Borrowing, Dangling References
  10. Go FAQ, How do I know whether a variable is allocated on the heap or the stack?
  11. The Python Standard Library, io, Python 3.14, IOBase.close
  12. Java SE 25 API, java.io.Reader, close
  13. .NET API, ObjectDisposedException Class, Remarks
  14. C# language reference, using statement, the using statement; the using declaration
  15. CodeQL query help, Potential use after free (cpp/use-after-free), the query description; Recommendation
  16. CVE-2014-1776, Microsoft Internet Explorer, the description and the publication date
  17. CVE-2020-6819, Mozilla Firefox, the description and the publication date
  18. CVE-2021-0920, Linux kernel in Android, the description and the publication date

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/0HDQ4M/text.yaml