skip to content

In a long-running Rust service, when is `Box::leak` an acceptable way to get a `&'static` reference, and what does it cost?

level: seniorimportance: should knowfreq 30%

answer

  1. memory meant to outlive everything
  2. once at startup, never per request
  3. destructors never run
  4. T must outlive the chosen lifetime

basics

~20 s

Box::leak safely turns a Box into a &'static mut by never freeing it. It suits data built once that must last the whole process, like startup config. Drop never runs, and leaking per request grows memory without bound.

solid answer

~40 s

`Box::leak` consumes a `Box<T>` and returns `&'a mut T` for a lifetime the caller picks, including `'static` when `T: 'static`. It is a safe function, called as `Box::leak(b)`. It fits values created **once** that must stay valid for the rest of the process: configuration loaded at startup and then shared with worker threads as a `Copy` `&'static Config`, or plugin names read once. The costs: the allocation is never freed, `Drop` never runs, so buffered writers are not flushed and handles are not closed by their destructors, and a leak inside a per-request path grows memory without bound. std documents unleaking with `Box::from_raw` as a grey area to avoid; if the value should be freed someday, use `Arc` or `Box::into_raw` instead.

code

rust · 29 lines
rust
use std::thread;

struct Config {
    endpoint: String,
    interval_ms: u64,
}

impl Drop for Config {
    fn drop(&mut self) {
        println!("Config dropped");
    }
}

fn load_config() -> &'static Config {
    let cfg = Box::new(Config {
        endpoint: String::from("udp://127.0.0.1:8125"),
        interval_ms: 500,
    });
    Box::leak(cfg) // &'static mut Config, coerced to &'static Config
}

fn main() {
    let cfg = load_config();
    let worker = thread::spawn(move || {
        println!("pushing to {} every {} ms", cfg.endpoint, cfg.interval_ms);
    });
    worker.join().unwrap();
    println!("main exits; Config is never dropped");
}

go deeper

for a junior

Recall that Box::leak turns a Box into a &'static mut reference by never freeing the memory.

for a middle

Explain the signature: the caller picks the lifetime, T must outlive it, and the function is safe because leaking is not undefined behaviour.

for a senior

Show production judgment: leak only bounded, once-built data such as startup config, remember Drop never runs, and flag any leak on a per-request or reload path in review.

for a principal

Decide a team rule for process-wide data: when a deliberate leak is clearer than Arc or a once-initialised global, and how reviews keep leaks out of hot paths.

## What `Box::leak` does `Box::leak` is declared in `alloc` as: ```rust pub fn leak<'a>(b: Self) -> &'a mut T where A: 'a, ``` It **consumes the box without freeing it** and hands back a mutable reference to the contents. The implementation takes the raw pointer out of the box and never hands it back to the allocator. Because nothing will ever deallocate that memory, the caller may choose any lifetime for the reference, including `'static`. std's doc comment adds the condition: `T` must outlive the chosen lifetime, so `'static` is available only if the type holds no short borrows. Leaking a `Box<Vec<&str>>` whose strings borrow a local still fails with E0597. Two practical details: - It is an **associated function**: you write `Box::leak(b)`, not `b.leak()`, so it cannot clash with a method on `T`. - It is **safe**. Leaking memory is not undefined behaviour in Rust, so no `unsafe` block is needed. ## When it is the right tool std describes the intended use: data that lives for the remainder of the program's life, memory that is meant to leak. In a service that means values built **once**, whose total size is fixed: 1. **Startup configuration** parsed from a file and then read by every worker thread. `&'static mut Config` coerces to `&'static Config`, which is `Copy`, so each `thread::spawn(move || ...)` gets its own copy of the pointer with no reference counting. 2. **Names or tables loaded once** and stored in a structure typed with `&'static str`, such as a plugin registry. 3. **Short-lived programs and tests**, where the process exit reclaims everything anyway. The real test is a bound on how many times the leak can happen. Leaking once per process is a fixed cost, much like a static item. Leaking once per configuration reload is tolerable only when reloads are rare and the values small, and that memory still never comes back. For strings and vectors there are direct forms. `String::leak` returns `&'a mut str` without reallocating, so any unused capacity stays in the leaked block; calling `into_boxed_str` first and then `Box::leak` trims the capacity, at the price of a possible reallocation. `Vec::leak` behaves like `String::leak` for slices. ## What it costs | Cost | Consequence | |---|---| | The allocation is never freed | memory stays reserved until the process exits | | `Drop` never runs | a buffered writer is not flushed, a guard's cleanup is skipped, a connection is not closed by its destructor | | Leaks add up | one leak per request or per reload grows memory without bound | | Unleaking is fragile | std calls rebuilding a `Box` with `Box::from_raw` a grey area that should be avoided | The `Drop` point surprises people: a leaked value is not dropped at program exit either. In the example below, a `Config` with a `Drop` impl that prints never prints. ## The anti-pattern: leaking to silence the borrow checker When `thread::spawn` or a `T: 'static` bound rejects a borrow, `Box::leak` makes the error disappear, and that is exactly why reviewers watch for it. Inside a request handler or a reload loop it turns a compile error into a slow memory leak that only shows up on a dashboard days later. Ask whether the data is created a bounded number of times; if not, use something that frees. ## Alternatives that do free memory - **`std::sync::Arc<T>`**: shared ownership across threads, freed when the last handle drops; reference counting is covered with Mutex, RwLock and Arc. - **A once-initialised global**, covered with OnceLock and LazyLock, when the value is process-wide and created on first use. - **Scoped threads**, covered with spawning and scopes, when the threads must finish before the data's owner returns. - **Owned data moved into the thread**, when only one thread needs it. - **`Box::into_raw`**, when you need a raw pointer now and intend to free it later with `Box::from_raw`, a subject of Box and heap allocation. ## A review checklist - Is the leaked value created once, or a bounded number of times? - Does its type have a `Drop` impl whose side effects matter? - Would `Arc` or a once-initialised global say the same thing while freeing memory? - Is the leaked size small and known, so memory graphs show a flat line rather than a slope?

  • Can memory obtained from `Box::leak` be freed later?
    std's doc comment says that rebuilding a `Box` from the returned reference with `Box::from_raw` is a grey area where many seemingly harmless ways are undefined behaviour, and should be avoided. If the memory should eventually be freed, use `Box::into_raw` instead, or share the value with `Arc`.
  • Why can `Box::leak` on a `Box<Vec<&str>>` that borrows a local not return `&'static mut`?
    The returned `&'a mut T` requires `T: 'a`, as std's doc comment notes: the type must outlive the chosen lifetime. `Vec<&str>` borrowing a local is not `'static`, so rustc 1.99 reports E0597 at the borrow. Leaking only extends the allocation, not the borrows inside it.

  • Box::leak is unsafe and must be wrapped in an unsafe block.
  • A leaked value's Drop implementation still runs when the program exits.
  • Box::leak is a fine fix whenever thread::spawn rejects a borrowed local.
  • Leaking a box makes every borrow inside its contents 'static too.
  • The allocator reuses leaked blocks, so repeated leaks keep memory flat.