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
} #4A 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

