In Rust, when do you use `Box::leak` rather than `Box::into_raw`, and what must eventually happen to the pointer `into_raw` returns?
answer
- never freed versus freed later
- a reference versus a raw pointer
- from_raw exactly once
- same allocator and layout
basics
~20 sBox::leak gives up the allocation for good and returns a &'a mut T, often 'static, for data that lives until exit. Box::into_raw returns a *mut T, and its owner must later pass it to Box::from_raw exactly once to drop and free it.
solid answer
~40 sBoth consume the box without running the destructor. `Box::leak` is safe and returns `&'a mut T` with a lifetime you choose, often `'static`, so it suits a config or lookup table built once and shared until exit; the memory returns at process exit but `Drop` never runs. `Box::into_raw` returns an aligned, non-null `*mut T` and is `#[must_use]` because losing it leaks; the owner later calls `unsafe { Box::from_raw(ptr) }` exactly once, which runs the destructor and frees the block. That pointer must have come from the global allocator with `Box`'s layout, and a second `from_raw` is a double free. std says to prefer `into_raw` or the `into_non_null` added in Rust 1.99 when memory must be freed, and not to rebuild a box from `leak`'s reference.
code
rust · 24 linesstruct Config {
region: String,
retries: u32,
}
fn main() {
// Built once at startup, read for the rest of the process.
let cfg: &'static Config = Box::leak(Box::new(Config {
region: String::from("eu-west-1"),
retries: 3,
}));
let handle = std::thread::spawn(move || cfg.retries);
println!("{} {}", cfg.region, handle.join().unwrap());
// A value that must be freed later: hand out a raw pointer, take it back once.
let raw: *mut Config = Box::into_raw(Box::new(Config {
region: String::from("us-east-1"),
retries: 5,
}));
// ... raw travels through a C callback's void* or an intrusive list ...
let back: Box<Config> = unsafe { Box::from_raw(raw) };
println!("{} {}", back.region, back.retries);
// `back` drops here: Config's String is freed, then the heap block.
}go deeper
Recall that Box::leak keeps a value alive until the program ends and Box::into_raw turns a box into a raw pointer you must give back later.
Explain the contracts: leak is safe and returns a reference with a chosen lifetime; into_raw is must_use, and from_raw is unsafe with conditions on allocator, layout and calling it once.
Pick the right one in a review: leak only for bounded startup data, into_raw for pointers lent to callbacks, NonNull for stored pointers, and flag leaks in loops or values whose Drop matters.
Set a team rule that every into_raw has a single documented from_raw site and that leak is limited to bounded startup data, so leaks and double frees are caught in review.
## Two ways to stop a `Box` from freeing its value A `Box<T>` frees its heap allocation when it is dropped: it runs `T`'s destructor and then returns the memory to the global allocator. Two associated functions consume a box **without** doing that, and they answer different questions. | | `Box::leak(b)` | `Box::into_raw(b)` | |---|---|---| | Returns | `&'a mut T`, where `T` must outlive `'a` | `*mut T`, aligned and non-null | | Safe to call? | yes | yes | | Memory freed later? | not meant to be | yes, by whoever owns the pointer | | Destructor runs? | never | when the box is rebuilt and dropped | | Typical use | data that lives until the process exits | a C callback's user data, an intrusive structure | Both are called as `Box::leak(b)` and `Box::into_raw(b)`, never `b.leak()` or `b.into_raw()`: they are associated functions so they cannot clash with a method on `T`. Writing `b.into_raw()` fails with E0599 and the note that it is an associated function, not a method. ## `Box::leak`: memory you will never give back `Box::leak` (stable since Rust 1.26) hands back a mutable reference whose lifetime you choose; if `T` holds no shorter-lived references, that can be `&'static mut T`, which coerces to `&'static T`. Use it for values built once at startup and read for the rest of the run: - a configuration parsed from a file and shared with every thread; - interned strings or lookup tables that live as long as the process; - a test fixture that must outlive a spawned thread. The memory is reclaimed by the operating system when the process exits, but **`Drop` never runs**: a buffered writer is never flushed and a temporary file is never deleted. Leaking is safe Rust, the same way `mem::forget` is safe; it is a resource cost, not undefined behaviour. Calling it in a loop or per request is an unbounded leak. The std documentation on 1.99 is explicit that if the memory should eventually be freed you should prefer `Box::into_raw` or `Box::into_non_null`. Rebuilding a box from the reference `leak` returned is possible only with the global allocator and is described as a grey area where many seemingly harmless ways of doing it are undefined behaviour. ## `Box::into_raw`: ownership travels as a raw pointer `Box::into_raw` (stable since Rust 1.4) gives up the box but not the obligation. The function is `#[must_use]` with the note "losing the pointer will leak memory", and the caller becomes responsible for destroying the value and releasing the memory. The normal way back is: ```rust let raw: *mut Config = Box::into_raw(Box::new(cfg)); // ... raw travels through a C callback's void* or an intrusive list ... let back: Box<Config> = unsafe { Box::from_raw(raw) }; // back drops here: Config's destructor runs, then the block is freed ``` `Box::from_raw` is `unsafe` because the compiler cannot check its contract. Its documentation lists what you promise: 1. The pointer came from the **global allocator** with the layout `Box` uses for that type, which is guaranteed when it came from `Box::into_raw`. 2. You call it **once** per pointer; calling it twice gives two boxes owning one block, a double free. 3. Nobody uses the raw pointer after the rebuilt box is dropped. A pointer from C's `malloc`, from a stack variable or from a different allocator does not meet the first condition. ## `NonNull` variants in Rust 1.99 Rust 1.99 stabilised `Box::into_non_null` and `Box::from_non_null`, which do the same round trip with `std::ptr::NonNull<T>` instead of `*mut T`. Use them when the pointer is stored in a struct field: the type records that it is never null, and `Option<NonNull<T>>` stays pointer-sized. `from_non_null` carries the same safety contract as `from_raw`. ## Choosing in review - The value lives until exit and nobody frees it: `Box::leak`. - The value is handed to code you do not control and comes back later: `Box::into_raw` now, `Box::from_raw` exactly once later. - The pointer sits in your own data structure: `Box::into_non_null`. - You just want the destructor skipped and will never need the pointer: neither; question why the value exists. The ownership rules of a full foreign-function boundary, such as who frees memory across a C library and how callbacks unwind, belong to the material on foreign function calls; raw pointer dereferences belong to the unsafe material.
- What happens to the `Drop` impl of a value passed to `Box::leak`?It never runs. The operating system reclaims the memory when the process exits, but anything `Drop` would have done, such as flushing a buffered writer or deleting a temporary file, does not happen. That is safe Rust, as `mem::forget` is, but it means leak suits plain data, not values that own outside resources.
- Why reach for `Box::into_non_null`, added in Rust 1.99, instead of `into_raw`?It returns a `NonNull<T>`, which records in the type that the pointer is never null and keeps `Option<NonNull<T>>` pointer-sized. That suits a pointer stored in your own struct field. `Box::from_non_null` rebuilds the box under the same safety contract as `from_raw`: global allocator, matching layout, called once.
- Box::leak is unsafe because leaking memory is undefined behaviour.
- Box::into_raw frees the value and returns a dangling pointer.
- Leak's reference can always be turned back into a Box with from_raw.
- Box::from_raw accepts any pointer, including one from malloc or the stack.
- Dropping the raw pointer from into_raw frees the allocation.
Assumes Rust 1.99, which stabilised Box::into_non_null and Box::from_non_null; Box::leak (1.26) and Box::into_raw and from_raw (1.4) are far older.