Sub topic 14
Reference cycles can leak memory
This chapter assumes you know Rc<T> and its strong count, RefCell<T> and borrow_mut, and the Drop trait. If you need to refresh any of these, read their chapters first. The chapter shows how two Rc values can keep each other alive forever. It also shows how to spot the problem. The fix, Weak<T>, comes in the next chapter.
Why Rust allows leaks
Rust's safety guarantees cover data races, dangling pointers, and use-after-free. They do not cover memory that is never freed. A leak is memory safe: the program never reads freed memory, it just never releases some. Rust therefore treats leaking as safe. The standard library even provides std::mem::forget and Box::leak, which leak on purpose.
Most Rust code never leaks, because ownership forms a tree and every value has one owner that drops it. Rc<T> breaks that tree shape. With several owners, a value is freed only when its strong count reaches zero. If a chain of Rc values points back to its own start, no count in the chain can ever reach zero.
How a cycle forms
A cycle needs two things:
- Shared ownership, so that values can point to each other.
Rc<T>provides this. - A way to change a link after creation. Without it, you could not point an older value at a newer one.
RefCell<T>provides this, usually asRc<RefCell<T>>or aRefCellfield holding anRc.
The following program builds two nodes and then makes each one point to the other.
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
name: &'static str,
next: RefCell<Option<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("dropping {}", self.name);
}
}
fn main() {
let a = Rc::new(Node {
name: "a",
next: RefCell::new(None),
});
let b = Rc::new(Node {
name: "b",
next: RefCell::new(Some(Rc::clone(&a))),
});
println!("before cycle: a = {}, b = {}", Rc::strong_count(&a), Rc::strong_count(&b));
*a.next.borrow_mut() = Some(Rc::clone(&b));
println!("after cycle: a = {}, b = {}", Rc::strong_count(&a), Rc::strong_count(&b));
}The output is:
before cycle: a = 2, b = 1
after cycle: a = 2, b = 2The Drop implementation never prints "dropping a" or "dropping b". Both nodes are leaked.
Following the counts
Before the cycle, a has two owners: the variable a and the next field inside b. Node b has one owner, the variable b. The line that sets a.next gives b a second owner, the next field inside a.
When main ends, locals drop in reverse order of declaration:
- Variable
bis dropped. The strong count ofbgoes from 2 to 1. It is not zero, so the node is not freed. - Variable
ais dropped. The strong count ofagoes from 2 to 1. It is not zero either. - The stack variables are gone, but each node is still owned by the other node's
nextfield.
Nothing can reach the two nodes anymore, but each one holds the other's count above zero. The heap memory stays allocated until the process exits.
The same structure without a cycle
The leak comes from the loop, not from Rc or RefCell themselves. Remove the line that sets a.next and the nodes drop normally.
use std::cell::RefCell;
use std::rc::Rc;
struct Node {
name: &'static str,
next: RefCell<Option<Rc<Node>>>,
}
impl Drop for Node {
fn drop(&mut self) {
println!("dropping {}", self.name);
}
}
fn main() {
let a = Rc::new(Node {
name: "a",
next: RefCell::new(None),
});
let _b = Rc::new(Node {
name: "b",
next: RefCell::new(Some(Rc::clone(&a))),
});
println!("a = {}", Rc::strong_count(&a));
}The output is:
a = 2
dropping b
dropping aVariable _b drops first and its count reaches zero. Dropping node b also drops its next field, which releases one count on a. Then variable a drops and its count reaches zero.
Common ways cycles appear
- Parent and child links. A tree where parents own children with
Rcand children also own parents withRc. - Doubly linked lists. Each node holds an
Rcto both neighbors. - Graphs. Nodes hold
Rchandles to neighbors, and the graph contains a loop. - Observers and callbacks. An object stores a closure that captures an
Rcof the object itself, or two objects register each other as listeners. - Self reference. A single node whose
RefCellfield holds anRcto itself is a cycle of length one.
A cycle can also be long and hard to see. Any path of strong links that returns to its starting value is enough.
Detecting cycles
The compiler cannot detect a cycle, because cycles are built at runtime. These techniques help:
- Log in
Drop. As above, if a value you expect to drop never prints, something still owns it. - Check
Rc::strong_count. A count that stays above what you expect after the last outside owner is gone points to a hidden owner. - Run under Miri. Miri is an interpreter for Rust's intermediate representation, used to find undefined behavior. By default it also reports memory still allocated when the program exits.
- Use a leak checker. Tools such as Valgrind or LeakSanitizer report memory that was allocated but never freed.
- Watch for memory growth. In a long-running program, a cycle created per request shows up as steadily rising memory use.
Why this is a design problem, not a language bug
A cycle is a case where the program's ownership description is ambiguous. If a owns b and b owns a, neither can be freed first. The reference-counting scheme has no way to resolve that, and it is not unique to Rust. Other reference-counted systems have the same weakness. Tracing garbage collectors avoid it by finding unreachable values from the roots, at the cost of a collector.
The practical response is to decide which direction of a relationship is ownership and which is only observation. In a tree, a parent owns its children. A child merely needs to look up at its parent without keeping it alive. Rust has a type for this non-owning link, Weak<T>, covered in the next chapter. A Weak reference does not increase the strong count, so it does not keep the value alive and cannot form a leaking cycle.
Summary of failure modes
| Situation | What happens | Detectable by |
|---|---|---|
| Two `Rc` nodes point to each other | Counts never reach zero, nodes leak | Missing `Drop` output, `strong_count`, Miri |
| One node holds an `Rc` to itself | Count never drops below 1 | Missing `Drop` output |
| Cycle created once at startup | Small, bounded leak | Leak checker at exit |
| Cycle created per request or event | Memory grows without bound | Monitoring memory use |
| `{:?}` on a cyclic structure | Stack overflow | Crash when printing |
Exercise
In the first program in this chapter, a and b each end with a strong count of 2 after the cycle is created. After main returns, what is each count, and why is "dropping a" never printed?
Show answer
Each count is 1. Dropping the variables b and then a lowers each count by one, from 2 to 1. The remaining count on each node comes from the other node's next field. Because neither count reaches 0, Drop::drop never runs for either node, so nothing is printed.
Exercise
Name two things a cycle needs in order to form with Rc, and say which standard type usually provides the second one.
Show answer
A cycle needs shared ownership, which Rc<T> provides, and a way to change a link after the values exist, which RefCell<T> usually provides. Without interior mutability you cannot point an older value at a newer one.
Exercise
A tree stores children as Vec<Rc<Node>> and each child also stores its parent as Rc<Node>. Why does this leak, and what kind of link should the child-to-parent direction be?
Show answer
The parent holds a strong count on each child and each child holds a strong count on the parent, so the counts can never reach zero after the last outside handle is dropped. The child-to-parent link should be a non-owning reference, Weak<Node>, which the next chapter introduces.