Answer#
Leaking memory is not a memory-safety violation, so the compiler does not forbid it. The guarantees of safe Rust are that you cannot read freed memory, write out of bounds, or race on data. A program that holds on to memory it no longer needs is still correct in that sense, and Rust's standard library explicitly allows it (std::mem::forget and Box::leak are safe functions).
The leaks you meet in practice come in three kinds:
- Reference cycles. With
Rc(orArc), two values that own each other keep each other's count above zero forever. - Deliberate leaks.
Box::leakturns an allocation into a&'static mutreference that is never freed. It is used on purpose for values that must live as long as the program, such as global configuration. - Growth that never ends. A cache, a queue or a
Vecthat only receives items. This is a logic bug in any language.
How to do it: see a cycle and fix it with Weak#
This program makes a cycle of two values, and a parent/child tree where the child points back to its parent with a Weak pointer. Weak does not own the value, so it does not keep it alive.
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct Leaky {
name: &'static str,
other: RefCell<Option<Rc<Leaky>>>,
}
impl Drop for Leaky {
fn drop(&mut self) {
println!("dropping {}", self.name);
}
}
struct Node {
name: &'static str,
parent: RefCell<Weak<Node>>,
children: RefCell<Vec<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("dropping {}", self.name);
}
}
fn main() {
{
let a = Rc::new(Leaky { name: "a", other: RefCell::new(None) });
let b = Rc::new(Leaky { name: "b", other: RefCell::new(Some(Rc::clone(&a))) });
*a.other.borrow_mut() = Some(Rc::clone(&b));
println!("cycle: a={} b={}", Rc::strong_count(&a), Rc::strong_count(&b));
} // neither "dropping a" nor "dropping b" is printed: the counts never reach zero
{
let parent = Rc::new(Node { name: "parent", parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]) });
let child = Rc::new(Node { name: "child", parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]) });
*child.parent.borrow_mut() = Rc::downgrade(&parent);
parent.children.borrow_mut().push(Rc::clone(&child));
println!("with Weak: parent strong={} weak={}", Rc::strong_count(&parent), Rc::weak_count(&parent));
} // both are dropped here
let kept: &'static mut Vec<u8> = Box::leak(Box::new(vec![0u8; 16]));
println!("a deliberately leaked buffer of {} bytes", kept.len());
}cycle: a=2 b=2
with Weak: parent strong=1 weak=1
dropping parent
dropping child
a deliberately leaked buffer of 16 bytesThe two Leaky values never print "dropping": that is the leak. The tree frees both nodes because the child's pointer to the parent is Weak.
Common mistakes#
- Assuming "Rust has no leaks". It has no unsafe memory errors; leaks are possible.
- Using
Rc<RefCell<T>>for a graph or tree with back-pointers, withoutWeakfor the back direction. - Treating a growing
HashMapcache as harmless. Put a bound on it (a maximum size or an expiry).
Related questions#
How do I find a leak in a Rust program?#
Compare the process's memory over time with a tool for your platform, and add a Drop implementation that prints (as above) to see which values are never freed. A heap profiler such as the ones that work with any native program (Valgrind on Linux, Instruments on macOS) also works on Rust.
Is Box::leak safe to call?#
Yes, it is a safe function. It gives up the ability to free that allocation, and nothing else.
Sources#
- The Rust Book, "Reference Cycles Can Leak Memory": https://doc.rust-lang.org/book/ch15-06-reference-cycles.html
- Standard library,
std::mem::forget: https://doc.rust-lang.org/std/mem/fn.forget.html