How Does Rust Prevent Dangling References?

Rust prevents dangling references by using a compile-time borrow checker to enforce lifetime rules, ensuring references never outlive the data they point to.

Rust prevents dangling references by using a borrow checker that enforces lifetime rules at compile time, ensuring references never outlive the data they point to. The compiler rejects code where a reference's lifetime exceeds the scope of the borrowed value, as shown in the error for Listing 10-16 where x does not live long enough for r. This guarantees memory safety without runtime overhead by refusing to compile invalid reference patterns.

// This code fails to compile because `x` is dropped before `r` is used
fn main() {
    let r;
    {
        let x = 5;
        r = &x; // ERROR: `x` does not live long enough
    }
    println!("r: {r}");
}

To fix this, ensure the data lives at least as long as the reference by moving the declaration outside the inner scope:

fn main() {
    let x = 5; // `x` lives for the entire function
    let r = &x; // Valid: `x` outlives `r`
    println!("r: {r}");
}