Accessing memory that has already been freed (deleted).
Use-after-free (UAF) is a critical memory error where a program continues to use a pointer after the memory it points to has been freed with `delete` or `free()`. The memory may be reallocated to something else, leading to unpredictable behavior, corrupted data, or exploitable security vulnerabilities.
Causes include: forgetting to set a pointer to `nullptr` after deleting it, multiple pointers to the same allocation (aliasing) where one is deleted while another is still used, returning local object references, or using an iterator after a container is modified.
1#include <iostream>2 3int main() {4 int* data = new int(100);5 6 std::cout << "Value: " << *data << std::endl; // OK7 8 delete data; // Memory is freed9 10 // BUG: Accessing freed memory!11 std::cout << "After delete: " << *data << std::endl;12 *data = 200; // Writing to freed memory — undefined behavior!13 14 return 0;15}1#include <iostream>2#include <memory>3 4int main() {5 // Fix 1: Set to nullptr immediately after delete6 {7 int* data = new int(100);8 std::cout << "Value: " << *data << std::endl;9 delete data;10 data = nullptr; // Prevent dangling pointer use11 // Accessing nullptr is still wrong but now detectable with a null check12 }13 14 // Fix 2 (BEST): Use smart pointers — no manual delete needed15 {16 std::unique_ptr<int> data = std::make_unique<int>(100);17 std::cout << "Value: " << *data << std::endl;18 // Memory is automatically freed when 'data' goes out of scope19 // Using 'data' after this block is a compile-time or runtime-detectable error20 }21 // 'data' is out of scope — no dangling pointer possible22 23 return 0;24}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
After `delete data;`, the memory that `data` points to is returned to the heap allocator. The pointer `data` becomes a "dangling pointer" — it still holds the old address, but that memory is no longer owned by this program. Any reads/writes through `data` after this are undefined behavior and can cause crashes, silent data corruption, or security vulnerabilities.