skip to content

In C++, after `delete p` runs, what happens to other raw pointers holding the same address, and what does deleting one of them again do?

level: middleimportance: should knowfreq 55%

answer

  1. delete ends the lifetime and frees storage
  2. copies of a pointer are not told
  3. invalid pointer value
  4. a second delete corrupts the allocator
  5. nulling one copy fixes only that copy

basics

~20 s

Every copy of the pointer becomes an invalid pointer value. Dereferencing any of them is a use-after-free and deleting any of them again is a double delete; both are undefined behaviour, often corrupting the heap long before anything crashes.

solid answer

~50 s

`delete p` runs the object's destructor and returns its storage to the allocator. Every raw pointer that held that address — `p` itself and all its copies — now holds an **invalid pointer value**. Indirection through one is undefined behaviour (**use-after-free**), and passing one to `delete` again is undefined behaviour (**double delete**); even copying or comparing such a pointer is implementation-defined. In practice a stale read returns old bytes or another object's data, a stale write corrupts whichever object reuses the block, and a double delete can corrupt the allocator's bookkeeping so that a later, unrelated `new` or `delete` crashes or aborts. Setting `p = nullptr` after the delete makes only that one variable safe to delete again; the copies still dangle. The real fix is a single owner: one object deletes, everyone else observes it with a lifetime they can check.

code

cpp · 17 lines
cpp
#include <iostream>
#include <string>

struct Texture { std::string name; int width = 0; };

struct Sprite {
    Texture* tex;                          // raw pointer, ownership unclear
    ~Sprite() { delete tex; }
};

int main() {
    Texture* t = new Texture{"grass", 64};
    Sprite a{t};
    Sprite b = a;                          // implicit copy: both hold the same pointer
    delete t;                              // third owner frees it early
    std::cout << a.tex->width << '\n';     // use-after-free: undefined behaviour
}                                          // ~b, then ~a: delete twice more

go deeper

for a junior

Recall that delete destroys the object and frees its memory, and that using or deleting the same address again is undefined behaviour.

for a middle

Explain that copies of the pointer are not updated, why nulling one variable does not help the others, and what the allocator does with a block freed twice.

for a senior

Trace ownership in a snippet: find the shallow copy, the observer that outlived the owner or the duplicated cleanup path, and fix the ownership rather than the symptom.

for a principal

Push the team toward code where application logic contains no bare delete, so every lifetime has one owner and reviewers check ownership instead of counting deletes.

## What `delete` actually does A `delete` expression does two things in order: 1. it calls the destructor of the object the pointer designates, ending that object's **lifetime**; 2. it calls a **deallocation function** (`operator delete`) to return the storage to the allocator. The pointer variable is untouched: it keeps the same bit pattern. Neither is any other pointer that happens to hold the same address. C++ has no mechanism that finds copies of a pointer and updates them. ## The standard's status of the leftover pointers When the storage is released, every pointer value that pointed into it becomes an **invalid pointer value**. The rules are short and strict: - **indirection** through an invalid pointer value (`*p`, `p->x`) is undefined behaviour; - passing it to a **deallocation function**, which is what a second `delete` does, is undefined behaviour; - any other use, such as copying it or comparing it to another pointer, has implementation-defined behaviour. So "it was deleted but I only compared it" is not a guaranteed-safe pattern either. ## What the two bugs do on a real machine | Bug | Typical effect | |---|---| | read after free | returns stale bytes or the fields of whatever object the allocator put there next | | write after free | silently overwrites another live object or the allocator's free-list metadata | | double delete | the block enters the allocator's free lists twice; two later `new` calls can receive the same address, or the allocator detects the corruption and aborts | | delete of a never-allocated address | undefined; allocators commonly abort with a diagnostic | None of these is guaranteed, which is the point: undefined behaviour gives the compiler and the allocator no obligation, and the visible failure often appears in a different function. ## How these bugs are usually created - **Shallow copies of an owning raw pointer.** A class that deletes a pointer in its destructor but keeps the implicit copy constructor gives two objects the same pointer; both destructors delete it. - **An owner and an observer that disagree about lifetime.** A cache, a parent object or a callback keeps a raw pointer after the owner freed the object. - **Manual cleanup on several paths.** An error path deletes, then the normal path deletes again. - **Mismatched forms.** Deleting a `new[]` array with plain `delete` is a different undefined-behaviour bug in the same family. ## Why `p = nullptr` is not the cure `delete nullptr` is a no-op, so nulling the variable after deleting it does stop that variable from being deleted twice. It does nothing for the copies, which is where these bugs live. It also turns a use-after-free through that one variable into a null dereference, which usually crashes at once but is still undefined behaviour. ## Reading a snippet for these bugs Interviewers usually show twenty lines and ask what is wrong. A reliable order of inspection: 1. Find every `new` and every `delete`, and pair them up by address, not by variable name. 2. For each allocation, list every variable, member or container element that ends up holding its address, including implicit copies made by copy constructors and assignments. 3. For each holder, check whether it is used after the matching `delete`, and whether it can reach a second `delete`. 4. Walk the destructors at the end of each scope, in reverse order of construction, because the double delete is often hidden there. The snippet below fails all four checks: an implicit copy duplicates the pointer, a third party deletes it, a read follows, and two destructors delete it again. ## Repairs that address the cause - Give every heap object **exactly one owner** whose lifetime controls the delete, and make that owner non-copyable or deep-copying. - Let observers hold a handle that can tell whether the object is still alive, or guarantee by design that observers die first. - Prefer types that delete for you; the ownership lessons cover `std::unique_ptr` and `std::shared_ptr`. - In review, treat every `delete` in application code as a question: who else holds this address?

  • Why can a double delete crash inside a later, unrelated new expression?
    The first delete puts the block on the allocator's free list; the second puts it there again. A later `new` may hand that address to one object and the next `new` to another, so two live objects share memory, or the allocator walks its corrupted list and aborts. The crash site is wherever the corruption is first noticed, not the second delete.
  • Is comparing a deleted pointer to nullptr safe?
    Not by guarantee. After the storage is released the pointer holds an invalid pointer value, and any use other than indirection or deallocation, including comparison, is implementation-defined. On common platforms it compares as a non-null address, which is exactly why `if (p) p->x` does not protect against use-after-free.

  • delete sets the pointer to nullptr, so a second delete is harmless.
  • Only the pointer passed to delete is affected; its copies remain usable.
  • A use-after-free always crashes immediately with a segmentation fault.
  • Checking if (p) before using the pointer prevents use-after-free.
  • Double delete just frees the memory twice, which wastes nothing.