skip to content

In Rust, why is `std::mem::forget` a safe function, and what does that mean for a type whose soundness depends on its Drop running?

level: seniorimportance: should knowfreq 30%

answer

  1. safety promise excludes something
  2. leaks are possible without forget
  3. unsafe code cannot trust destructors
  4. leak amplification in Vec::drain

basics

~20 s

Rust's safety guarantees do not include destructors always running: safe code can already leak through an Rc cycle or std::process::exit. So mem::forget is safe, and unsafe code must stay sound even if a value's Drop never runs.

solid answer

~40 s

`mem::forget` takes ownership and never runs the destructor. It is safe because leaking is not undefined behaviour: the value becomes unreachable, so nothing can misuse it, and safe code already has other ways to skip destructors, such as an `Rc` cycle through interior mutability or `std::process::exit`. The consequence lands on **unsafe** code: a type may not rely on its `Drop` running to stay **sound**. A proxy type that leaves shared state inconsistent until its destructor repairs it must instead make the leaked state safe. `Vec::drain` does this by shortening the vector to the start of the range up front, so forgetting the `Drain` leaks elements but never exposes moved-out slots. Forgetting a pool guard is a bug, not UB.

code

rust · 17 lines
rust
struct PoolGuard(u32);

impl Drop for PoolGuard {
    fn drop(&mut self) {
        println!("guard {} released", self.0);
    }
}

fn main() {
    let leaked = PoolGuard(1);
    std::mem::forget(leaked); // safe: no unsafe block, destructor never runs
    let dropped = PoolGuard(2);
    drop(dropped);
    let _never = PoolGuard(3);
    println!("exiting");
    std::process::exit(0); // destructors of live locals do not run
}

go deeper

for a junior

Recall that mem::forget skips a value's destructor, is not unsafe, and that a leak wastes resources but is not undefined behaviour.

for a middle

List the safe ways a destructor can be skipped, an Rc cycle, process::exit, an abort, and explain why that made marking forget unsafe pointless.

for a senior

Show the consequence for unsafe code: a proxy type must leave a safe state if its Drop never runs, as Vec::drain does by shortening the vector first, which the Rustonomicon calls leak amplification.

for a principal

Review unsafe abstractions for hidden reliance on Drop, and prefer closure-scoped APIs, as std::thread::scope does, wherever soundness would otherwise hinge on a guard being dropped.

## What `mem::forget` does `std::mem::forget(value)` takes ownership of a value and **does not run its destructor**. Whatever the value managed, heap memory, a file handle, a pooled connection, lingers in an unreachable state. It is not a way to free memory; the standard library implements it as nothing more than wrapping the value in `ManuallyDrop`, which suppresses the automatic drop. It is an ordinary safe function, callable without an `unsafe` block. Its documentation gives the reason directly: Rust's safety guarantees **do not include a guarantee that destructors will always run**. ## Why leaking is not a safety problem Safety in Rust means the absence of undefined behaviour: no use-after-free, no data races, no reads of invalid values. A leaked value is **unreachable**, so no code can use it after it has been "freed"; its memory simply is not reclaimed. That is wasteful and often a bug, but it is memory-safe. More importantly, safe Rust could already skip destructors before `forget` entered the picture, so marking it `unsafe` would have protected nothing: - an `Rc` reference cycle built through interior mutability keeps every member's count above zero forever; - `std::process::exit` and `std::process::abort` end the process without unwinding, so live locals are never dropped; - with the `abort` panic strategy, a panic ends the process without running destructors; - a program can fill a collection and then loop forever without touching it. `mem::forget` was once marked `unsafe` as a kind of lint, before Rust 1.0; the Rustonomicon records that this stance was judged untenable for exactly these reasons. ## The rule this imposes on unsafe code Safe code may reasonably assume leaks do not happen, because a program that leaks destructors is probably wrong. **Unsafe code may not**: it cannot rely on a destructor running in order to be sound. You cannot hand out a value and assume the caller will drop it. For most types this costs nothing. If you leak a `Box<u8>`, you waste a byte. The danger is in **proxy types**, values that manage access to something they do not own and leave it in a temporarily invalid state that their destructor repairs. ## How the standard library stays sound 1. **`Vec::drain`.** While a `Drain` iterator is live, some elements of the vector have been moved out and others have not. If the vector's length stayed unchanged until `Drain` was dropped, forgetting the `Drain` would leave the vector pointing at moved-out slots, and reading them would be a use-after-free. So `Vec::drain` **shortens the vector's length to the start of the range as soon as it is called** and restores the tail in `Drain`'s destructor. If the destructor never runs, the vector is merely shorter than expected and elements leak. The Rustonomicon calls this **leak amplification**: a leak causes more leaking, never unsoundness. 2. **`Rc`.** Forgetting clones of an `Rc` inflates its strong count without a matching decrement, and in principle the count could overflow and wrap to zero while handles remain. `Rc` therefore **aborts** the process if the count would overflow, rather than ever reaching that state. 3. **Scoped threads.** An early standard library API, since removed, returned a guard whose destructor joined a borrowing thread; forgetting the guard let the thread outlive the data it borrowed, so it was removed. Today's `std::thread::scope` takes a closure and joins every thread before it returns, without trusting any guard to be dropped. ## What this means for a guard you write | Guard behaviour | If the guard is forgotten | Acceptable in safe Rust? | |---|---|---| | returns a connection to a pool | a pool slot is lost for good | yes: a bug, not UB | | deletes a temporary file | the file stays on disk | yes: a bug, not UB | | restores a length or pointer that safe code reads | stale state exposed to safe code | **no**: unsound, redesign so the leaked state is valid | "Safe" is not the same as "harmless". A forgotten pool guard permanently shrinks the pool, and under load a service can end up waiting for connections that will never come back. That is a liveness bug rather than a memory-safety bug, which is why a `mem::forget` on a guard still deserves a question in review even though it compiles without `unsafe`. Legitimate uses of `mem::forget` exist, mainly when ownership of a resource has been handed to code outside Rust, such as passing a raw file descriptor to C. Even there, the documentation notes that `ManuallyDrop` is typically preferred.

  • When does a destructor of a live local not run, without any call to `mem::forget`?
    When the process ends without unwinding: `std::process::exit`, `std::process::abort`, or a panic under the `abort` panic strategy. Also when the value is kept alive forever, for example by an `Rc` cycle. An ordinary `return`, `?`, `break` or an unwinding panic does run the destructors of the locals it leaves.
  • Why does `Vec::drain` shorten the vector when it is created instead of when the `Drain` is dropped?
    Because the destructor is not guaranteed to run. Setting the length to the range start up front means that, if the `Drain` is forgotten, the vector exposes no moved-out slots; it just loses elements. The destructor then restores the tail in the normal case.
  • Is `mem::forget` the right tool for handing a buffer's memory to another owner?
    Usually not. The standard library recommends `ManuallyDrop` instead: with `forget`, a panic between building the new owner and the `forget` call would drop the memory twice, and the original value may already be invalid when it is passed to `forget`.

  • mem::forget needs an unsafe block because skipping a destructor causes undefined behaviour.
  • Leaking memory is undefined behaviour in Rust.
  • Safe Rust guarantees that every destructor eventually runs.
  • mem::forget frees the heap memory and only skips the custom Drop code.
  • std::process::exit unwinds the stack and drops live locals first.