liveBook · Manning

Use-after-free error

As explained in Memory Safe C++

Use-after-free is an error in which a program accesses memory after it has been deallocated.

A program can appear to work after reading freed memory, then produce garbage or crash in another build. A use-after-free error occurs when a program accesses memory after it has been deallocated. It is a temporal memory safety violation: the problem is when the access happens, not whether the pointer’s address has changed. section 2.4.2

Listing 2.3 A temporal violation: accessing freed memory
#include <iostream>
 
int main() {
   int* ptr = new int(42);
   delete ptr;                     #1
 
   int value = *ptr;               #2
   std::cout << value << "\n";     #3
}

The pointer retains its address after delete, but the integer is gone. Dereferencing the pointer is undefined behavior. section 2.4.2

Undefined behavior has no defined result. In the example, a read might appear to return the original value, return garbage, or crash. Observed results and compiler warnings vary with the compiler, platform, and optimization level; a seemingly correct result does not make the access safe. section 2.4.2

Listing 2.4 Smart pointers to prevent temporal violations
#include <iostream>
#include <memory>
 
int main() {
   auto ptr = std::make_unique<int>(42);  #1
 
   int value = *ptr;               #2
   std::cout << value << "\n";     #3
} #4

A unique smart pointer owns the integer while it is read and releases it automatically when it goes out of scope. This avoids the manual deletion that caused the earlier use-after-free, but does not make every dereference safe. section 2.4.2

Avoiding one faulty pattern is not a complete safety process. Recognizing use-after-free, applying safe practices consistently, and supporting them with automated checks and a team culture that values safety all contribute to memory safety. section 2.4.2 section 1.7

How Memory Safe C++ covers it

How deep it goes
Explains a freed-pointer dereference, its undefined behavior, observed build differences, and a unique-ownership alternative.
Examples
Compares a deleted heap integer read through a raw pointer with an integer owned by a unique smart pointer.
What you can do after
Evaluate a dereference for access after deletion and understand why an apparently correct result does not establish safety.
How it connects
Connects use-after-free with temporal memory safety, undefined behavior, smart pointers, and memory safety practices.

Also explained in

Compare how 2 books explain use-after-free error →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Memory Safe C++. The section links point to the parts of the book it draws on.