Sub topic 14
Reference cycles can leak memory
This chapter assumes you know how Rc<T> counts owners, how RefCell<T> allows mutation through a shared reference, and how Drop runs when a value goes out of scope.
Why Rust allows leaks
Rust guarantees memory safety. It does not guarantee that every value is freed. A leak is not undefined behavior, so safe code is allowed to leak.
Rc<T> frees its value when the strong count reaches zero. If two values hold Rc pointers to each other, each keeps the other's count above zero. Neither count can reach zero, so neither value is ever dropped.
Building a cycle
RefCell lets us change a node after it has been shared, and that is what makes a cycle possible. The Drop implementation prints a message, so a leak shows up as a missing line.
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))),
});
// Close the loop: a now points to b.
*a.next.borrow_mut() = Some(Rc::clone(&b));
println!("a strong = {}", Rc::strong_count(&a));
println!("b strong = {}", Rc::strong_count(&b));
}The program prints:
a strong = 2
b strong = 2No "dropping" line appears. Each node has two owners: its variable in main and the other node's next field.
What happens at the end of main
When main returns, the variables b and then a go out of scope. Each drop lowers a count from 2 to 1, not to 0. The two nodes still own each other, but nothing else can reach them. They stay on the heap until the process exits.
After the variables are gone, only the two arrows between the nodes remain. Each node keeps the other alive.
Spotting cycles
- Look for types that combine
Rcwith interior mutability, such asRc<RefCell<T>>orRefCell<Option<Rc<T>>>. Without mutation after sharing, you cannot close a loop. - Check
Rc::strong_countin tests. A count that stays above zero after you expect the last owner to be gone suggests a cycle. - Use
Dropwith a print statement, as above, to confirm that values are freed. - Avoid printing a cyclic structure with
{:?}. TheDebugoutput follows the loop forever and overflows the stack.
Avoiding cycles
Rust cannot detect cycles at compile time, so you design them out. Decide which direction of a relationship expresses ownership. Parents own children, for example, but children do not own parents. Ownership uses Rc. The other direction should use a pointer that does not keep the value alive. The next chapter introduces Weak<T> for this purpose.
Exercise
In the example, why does the program print no "dropping" lines even though a and b go out of scope at the end of main?
Show answer
Each node's strong count is 2 (its variable plus the other node's next field). Dropping the variables lowers each count to 1, not 0. Since the counts never reach 0, Drop never runs and the nodes leak.
Exercise
Why is a cycle hard to create with Rc<T> alone, without RefCell<T>?
Show answer
Rc<T> gives only shared, immutable access. A node must exist before anything can point to it, and without interior mutability you cannot change an existing node afterward to point back, so the loop cannot be closed.