Sub topic 11
Dangling references and how Rust rejects them
This chapter assumes you know the borrowing rules for &T and &mut T, how scope and Drop work, and how to read a compiler error. It builds on the previous chapter, which covered the borrow checker.
What a dangling reference is
A dangling reference points to memory that has already been freed. In C and C++, using one is undefined behavior. It can crash, return garbage, or leak data. Rust refuses to compile any program that could create one.
The cause is always the same. A reference outlives the value it points to. The owner goes out of scope, Drop runs, and the reference is left pointing at freed memory.
The classic mistake
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{r}");
}This fails with error[E0597]: x does not live long enough. The compiler reports that x is dropped at the end of the inner block while it is still borrowed, and that the borrow is later used by println!.
The compiler compares two regions of code. One is how long the owner lives. The other is how long the reference is used. If the reference is used after the owner is gone, the program is rejected.
Returning a reference to a local
The same problem appears in functions. This is the form you are most likely to hit in real code.
fn make_greeting() -> &String {
let s = String::from("hello");
&s
}The compiler gives error[E0106]: missing lifetime specifier. The function takes no inputs, so the returned reference has nothing to borrow from. Even with a lifetime written out, s is dropped when the function returns, so the reference could never be valid.
Fixes
Return the owned value and move ownership to the caller:
fn make_greeting() -> String {
String::from("hello")
}
fn main() {
let g = make_greeting();
println!("{g}");
}For the scope example, move the owner to an outer scope so it lives as long as the reference:
fn main() {
let x = 5;
let r = &x;
println!("{r}");
}If a function returns a reference, it must borrow from one of its parameters. The next chapter shows how lifetime annotations describe that link.
Common errors
| Error | Meaning | Usual fix |
|---|---|---|
| `E0597` borrowed value does not live long enough | The owner is dropped while a reference is still used | Extend the owner's scope, or stop using the reference sooner |
| `E0106` missing lifetime specifier | A returned reference has no clear source | Return an owned value, or borrow from a parameter |
| `E0515` cannot return reference to local variable | The function returns a borrow of its own local | Return the owned value |
Exercise
This function does not compile. Why, and how do you fix it? fn build() -> &str { let s = String::from("hi"); &s }
Show answer
The returned reference borrows the local s, which is dropped when build returns, so the reference would dangle. Return the owned value instead: fn build() -> String { String::from("hi") }.