Sub topic 6
Dangling references and how Rust rejects them
This chapter assumes you know ownership and moves, shared (&T) and mutable (&mut T) references, and the rule that a value has either many readers or one writer. You should also be able to read a cargo build error. Here you will learn what a dangling reference is, the forms it takes in Rust code, and which compiler errors report it.
What a dangling reference is
A dangling reference points to memory that has been freed or reused. Reading through it is a use-after-free bug. In C and C++ this compiles and may crash, print garbage, or leak data to an attacker. Rust turns the bug into a compile error.
The rule that makes this possible is simple: a reference must never outlive the value it points to. The owner of a value drops it at a known point, the end of its scope or an explicit drop call. Every reference to that value must be finished before then.
The compiler checks this statically. It compares where each reference is created and last used against where each owner is dropped. No run-time check is needed, so safe code pays no cost for the guarantee.
The classic case: returning a reference to a local
This is the first form to learn. It does not compile:
fn dangle() -> &String {
let s = String::from("temp");
&s
}
fn main() {
let _r = dangle();
}The compiler stops with an error like this:
error[E0106]: missing lifetime specifier
--> src/main.rs:1:16
|
1 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed fromRead the help line closely. The function has no parameters, so the returned reference cannot borrow from anything the caller passed in. The only candidate is s, which belongs to the function and is dropped when it returns. Returning &s would hand the caller a pointer to freed memory.
The error code is E0106, a missing lifetime specifier. The compiler does not yet say "dangling". It reports that it cannot find any input the reference could come from. The next section shows how the error changes once you supply a lifetime.
What if you add a lifetime?
You might try to quiet the compiler by naming a lifetime:
fn dangle<'a>() -> &'a String {
let s = String::from("temp");
&s
}
fn main() {
let _r = dangle();
}This still fails, with a different error:
error[E0515]: cannot return reference to local variable `s`
--> src/main.rs:3:5
|
3 | &s
| ^^ returns a reference to data owned by the current functionA lifetime annotation never extends how long a value lives. It only describes a relationship that the compiler then checks. Here you claimed the result lives for 'a, which the caller chooses. The compiler found that s cannot satisfy that claim.
Fixing the function-return case
There are four common fixes. Pick the one that matches who should own the data.
- Return the owned value. Moving
sout transfers ownership to the caller, so nothing dangles. - Return a
'staticreference. This works only for data that lives for the whole program, such as string literals. - Borrow from a parameter. The caller owns the data and lends it. The result is tied to the argument.
- Take a buffer to fill. The caller supplies
&mut Stringand the function writes into it.
fn owned() -> String {
let s = String::from("temp");
s
}
fn literal() -> &'static str {
"temp"
}
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn fill(out: &mut String) {
out.push_str("temp");
}
fn main() {
let a = owned();
let b = literal();
let text = String::from("borrowing is useful");
let c = first_word(&text);
let mut d = String::new();
fill(&mut d);
println!("{a} {b} {c} {d}");
}In first_word, the result borrows from text in main. text lives until the end of main, so c is always valid when it is used. The elision rules, covered in a later chapter, tie the output lifetime to the single input reference automatically.
Dangling through scope
You do not need a function to create a dangling reference. An inner block that ends too early is enough. This does not compile:
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}error[E0597]: `x` does not live long enoughx is dropped at the closing brace of the inner block. r is used after that point, so the borrow would outlast its owner. The fix is to move the owner outward, so that it lives at least as long as the last use of the reference:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}Notice that the error is about the last use of r, not the existence of r. If you delete the println!, the original program compiles. This follows from non-lexical lifetimes, which you met in the previous chapter.
Dangling through a move or drop
A value can also disappear because its owner moved it away or dropped it while a borrow was still live. This does not compile:
fn main() {
let s = String::from("x");
let r = &s;
drop(s);
println!("{r}");
}error[E0505]: cannot move out of `s` because it is borroweddrop(s) takes s by value, which ends its life. The later use of r would read freed memory. Moving s into another variable, a struct, or a thread triggers the same error, because a move ends the borrow's validity just as a drop does.
The same logic explains the earlier Vec example, where v.push(4) was rejected while first was alive. push may reallocate the buffer and free the old one. A reference into the old buffer would then dangle. The compiler cannot know whether a given push reallocates, so it forbids the whole pattern. This is why the borrowing rules and dangling prevention are two sides of the same guarantee.
The diagram below summarizes how to decide.
Quick reference for the errors
| Code | Message | Cause | Typical fix |
|---|---|---|---|
| E0106 | missing lifetime specifier | Returned reference has no input to borrow from | Return an owned value, or add a reference parameter |
| E0515 | cannot return reference to local variable | Lifetime is named but points at a local | Return the value itself, or borrow from a parameter |
| E0597 | borrowed value does not live long enough | Owner's scope ends before the last use of the reference | Move the owner to an outer scope |
| E0505 | cannot move out of value because it is borrowed | Owner moved or dropped while a reference is live | Use the reference first, or clone before moving |
Common mistakes
- Reaching for
'static. The compiler sometimes suggests'staticfor E0106. For a local value this is wrong. The suggestion text itself says it is "likely not what you want". Fix the ownership instead. - Returning a reference to a by-value parameter. A parameter of type
Stringis owned by the function, sofn f(s: String) -> &strhas the same problem as a local variable. Take&stror returnString. - Cloning to silence the error. Cloning is fine when the caller really needs an independent copy. Do not clone just to avoid thinking about who owns the data. Clone first, then check that the design still makes sense.
- Thinking the compiler is being conservative. In the dangling cases above, the program would have undefined behavior in a language without these checks.
Exercises
Exercise
This function fails with E0106. Explain why, and rewrite it so it compiles and returns the same text. fn make_greeting(name: &str) -> &str { let g = format!("Hello, {name}"); &g }
Show answer
The returned reference would point to g, which is created inside the function and dropped when it returns. The compiler also cannot connect the output to the input, since the result does not come from name. The fix is to return the owned value: fn make_greeting(name: &str) -> String { format!("Hello, {name}") }. The caller then owns the new text.
Exercise
The program below fails with E0597. Which variable is the problem, and what is the smallest change that makes it compile? fn main() { let longest; { let s = String::from("scoped"); longest = &s; } println!("{longest}"); }
Show answer
s is the problem. It is dropped at the end of the inner block, but longest is used afterward. The smallest fix is to declare s before the block, in the outer scope, so that it lives until the end of main. For example: let s = String::from("scoped"); let longest = &s; println!("{longest}");. Moving the println! into the inner block would also work.