MiddleDebuggingCommonNot answered yet
What happens if you access memory after delete? Does it always crash?
This code reads through a pointer after deleting it. In testing it often prints the right value, but in production it reads stale data, corrupts another object, or crashes.
void run() {
int* p = new int(42);
delete p;
// ... unrelated work ...
std::cout << *p << '\n';
}
Identify the bug and explain the cause.
Access after delete is undefined behavior. It may crash, appear to work, read stale data, corrupt another object, or fail later. The allocator is allowed to reuse that block immediately, and the language gives no guarantees.
- ✗Treating a non-crashing test run as evidence that the code is safe
- ✗Setting one pointer to nullptr and forgetting that aliases still dangle
- ✗Returning references or pointers to local variables
- →How do AddressSanitizer and Valgrind detect use-after-free?
- →How does RAII reduce this class of bugs?