Sub topic 11
Dangling references and how Rust rejects them
This chapter assumes you know shared and mutable references, the borrowing rules from the previous chapters, and basic scoping. You should also be comfortable reading rustc error output.
What a dangling reference is
A dangling reference points to memory that has already been freed or reused. In C and C++, using one is undefined behavior. It may crash, return garbage, or silently corrupt data. Typical sources are returning a pointer to a local variable, or keeping a pointer into a buffer that was later reallocated.
Rust has no garbage collector, so values are freed deterministically when their owner goes out of scope. A reference never owns what it points to. The compiler therefore has to prove that every reference is used only while its target is still alive. If it can't prove this, the program is rejected. Safe Rust has no dangling references.
The classic case: returning a reference to a local
This function creates a String inside its body and tries to return a reference to it:
// Does not compile.
fn dangle() -> &String {
let s = String::from("hello");
&s
}
fn main() {
let r = dangle();
println!("{r}");
}s is owned by dangle, so it is dropped when dangle returns. The returned reference would point at freed heap memory. The compiler reports error E0106, "missing lifetime specifier". The message notes that the return type contains a borrowed value, but there is no value for it to be borrowed from.
The message talks about lifetimes because that is how the compiler reasons about the problem. The next chapter covers lifetime annotations. For now, remember that a returned reference must borrow from something that outlives the call.
If the function has a parameter to borrow from, the signature compiles. The body is then rejected instead:
// Does not compile.
fn first_or_default(input: &str) -> &str {
let fallback = String::from("default");
if input.is_empty() {
&fallback
} else {
input
}
}Here the error is E0515, "cannot return reference to local variable fallback". The input branch is fine because the caller owns that data. The fallback branch is not.
Fixing it: three options
Which fix you choose depends on who should own the data.
| Situation | Fix | Result |
|---|---|---|
| The function creates new data | Return the owned value | Ownership moves to the caller |
| The result is a piece of an argument | Return a reference derived from the argument | The caller's data is borrowed |
| The data is fixed at compile time | Return a string literal | The `'static` data lives for the whole program |
fn no_dangle() -> String {
let s = String::from("hello");
s
}
fn first_or_empty(input: &str) -> &str {
input.split_whitespace().next().unwrap_or("")
}
fn greeting() -> &'static str {
"hello"
}
fn main() {
let owned = no_dangle();
let word = first_or_empty("alpha beta");
println!("{owned} {word} {}", greeting());
}Returning s moves it out, so the drop at the end of the function never happens. unwrap_or("") works in first_or_empty because string literals are 'static and can stand in for any shorter borrow.
Rejecting a borrow that outlives its owner
A reference can also dangle inside a single function, without any return value:
// Does not compile.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}The compiler reports E0597, "x does not live long enough". It also marks where x is dropped and where the borrow is used later. The error output points at three places:
- The borrow,
&x. - The end of the inner block, where
xis dropped. - The later use of
r.
The error exists only because the use in step 3 comes after step 2. If println! moved inside the inner block, the program would compile. Borrows end at their last use, so the compiler checks whether the target is still alive at each use of the reference.
Moving or dropping while borrowed
Ownership operations can also invalidate a live reference. Moving a value, or dropping it explicitly, ends the owner's control over it:
// Does not compile.
fn main() {
let s = String::from("hello");
let r = &s;
drop(s);
println!("{r}");
}The error is E0505, "cannot move out of s because it is borrowed". drop(s) takes ownership, frees the heap buffer, and leaves r pointing at freed memory. Rust rejects this at the call to drop. Swapping the last two lines fixes it, because r is no longer used when s is dropped.
Reallocation is a related case. Pushing to a Vec while you hold a reference to one of its elements can move the buffer to new memory. The old reference would then dangle. The borrowing rules forbid this, because push needs &mut Vec while the element reference holds a shared borrow.
Common mistakes and what to do
- Returning
&localor&local[..]. Return the owned value, such asStringorVec<T>, instead. - Returning
local.as_str(). This is the same bug as returning&local. The slice borrows from a value that is about to be dropped. - Storing a reference to a temporary. A reference to a value that exists only for one expression can't be kept past the statement that created it. Bind the value to a variable first. Rust extends the life of some temporaries bound directly with
let, but you shouldn't rely on it for method-call results. - Fighting the compiler with
cloneeverywhere. Cloning to dodge a borrow error is sometimes right, but first ask who should own the data. Often the answer is to restructure so the owner lives in a wider scope. - Reaching for
'static. The compiler'shelptext sometimes suggests&'static. That is correct only for data that really lives for the whole program, such as literals. Adding it to a reference to local data produces a different error.
Reading the error as a lifetime problem
Every reference has a lifetime, which is the region of code where it is valid. A dangling reference is a reference whose lifetime is longer than the lifetime of the data it points to. The borrow checker compares the two. Errors E0597, E0505, and E0515 are three views of this one comparison.
You rarely write lifetimes by hand, because the compiler infers them inside function bodies. At function boundaries, where the compiler can't see the caller's data, you sometimes must state how input and output references relate. That is the subject of the next chapter.
Exercise
This function does not compile. Explain why, then give two different ways to fix it. fn make_label(id: u32) -> &str { let label = format!("item-{id}"); &label }
Show answer
label is a String owned by make_label. It is dropped when the function returns, so &label would point at freed memory. There is also no input reference for the return value to borrow from, so the compiler reports a missing lifetime specifier (E0106). One fix is to return the owned value: fn make_label(id: u32) -> String { format!("item-{id}") }, which moves ownership to the caller. The other is to have the caller own the storage and pass it in, for example fn make_label(buf: &mut String, id: u32) -> &str { buf.clear(); buf.push_str(&format!("item-{id}")); buf.as_str() }. The returned slice then borrows from buf, which outlives the call. Returning a 'static literal also works, but only if the text doesn't depend on id.
Exercise
In the E0597 example with r and x, what single change makes the program compile without changing what it prints?
Show answer
Move the println!("{r}") line inside the inner block, after r = &x;. The last use of r then happens while x is still alive. Declaring x in the outer scope, before r, also works.