Sub topic 6
Dangling References and How Rust Rejects Them
This chapter assumes you know Rust syntax, String and &str, how moves work, and how shared and mutable references behave. You should also be able to build and run a program with cargo.
What a dangling reference is
A dangling reference points to memory that has already been freed or reused. In C and C++ this causes use-after-free bugs, which can crash a program or leak data. Rust rejects such code at compile time, so a safe Rust program cannot contain one.
The rule comes from ownership. A value is dropped when its owner goes out of scope. A reference must never outlive the value it points to.
The classic mistake
This function tries to return a reference to a local variable:
fn dangle() -> &String {
let s = String::from("temp");
&s
}
fn main() {
let _r = dangle();
}This does not compile. The variable s owns the String. When dangle returns, s is dropped and its heap memory is freed. The returned &s would point at freed memory.
The compiler reports error E0106, "missing lifetime specifier". It adds a help note: "this function's return type contains a borrowed value, but there is no value for it to be borrowed from". The return type &String has no input reference to borrow from, so no lifetime can make it valid.
The fixes
There are two ways to fix this, and which one you pick depends on who should own the data.
Return the owned value
Move the value out of the function. Ownership transfers to the caller, so nothing is dropped early:
fn not_dangling() -> String {
let s = String::from("temp");
s
}
fn main() {
let r = not_dangling();
println!("{r}");
}This is the usual fix when a function creates new data.
Borrow from an input
If the data already lives in the caller, return a reference derived from a parameter. The caller's value outlives the call, so the reference stays valid:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}The returned &str is a slice of the input. The compiler ties its lifetime to the single input reference, so word is valid while sentence is alive.
Dangling through scope
References can also dangle without a function call. If a reference outlives the variable it points to because of an inner block, the compiler stops you:
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}This does not compile, with error E0597, "x does not live long enough". The variable x is dropped at the closing brace, but r is used afterwards. Moving x into the outer scope, or moving the println! inside the block, fixes it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| E0106 on a return type `&T` | No input reference to borrow from | Return `T` by value |
| E0597 `does not live long enough` | Reference used after its owner's scope ended | Widen the owner's scope or shorten the reference's use |
| E0515 `returns a reference to data owned by the current function` | Returning `&local` or `local.as_str()` | Return the owned value |
Why the compiler can check this
Rust compares how long each value lives with how long each reference is used. A reference is only accepted when the value it points to lives at least as long as the reference does. The next chapters cover the tools for expressing and relaxing that comparison: non-lexical lifetimes and lifetime annotations.
Exercise
This function does not compile. Why, and how do you fix it so that it returns the greeting? fn greeting() -> &str { let s = String::from("hello"); s.as_str() }
Show answer
The String s is owned by the function and dropped when it returns, so s.as_str() would point to freed memory. The compiler rejects it because the return type has no input reference to borrow from. Change the return type to String and return s. Alternatively, return a string literal, which has type &'static str and lives for the whole program, with fn greeting() -> &'static str { "hello" }.