Course contentsShow
← Rust
Lesson 104 of 1,9102. The Ownership ModelFree lesson

Dangling References and Safety

Use the borrow checker to identify and prevent the use of invalidated memory locations.

In this lesson, you will learn how the Rust compiler prevents "dangling references," which are pointers that point to memory that has already been deallocated.

The Problem: Dangling References

A dangling reference occurs when you create a reference to a variable, but the variable itself is destroyed (goes out of scope) before you try to use that reference. In many languages, this leads to "undefined behavior" or crashes, because you end up accessing memory that has been reclaimed by the system for other purposes.

Consider this invalid Rust code:

fn main() {
    let reference_to_nothing = {
        let x = 42;
        &x // Return a reference to x
    }; // x is dropped here, so the reference points to invalid memory

    println!("{}", reference_to_nothing); // Error!
}

How the Borrow Checker Saves You

In the snippet above, the variable x is created inside a small inner block. When that block ends, x is cleaned up by its destructor. If we try to return a reference to x (&x), we are essentially trying to point to a piece of the stack that no longer contains our data.

Rust’s Borrow Checker analyzes the lifetime of every reference. It sees that x lives only until the end of the inner block, but the reference reference_to_nothing is trying to "outlive" the data it points to. Because the compiler can prove that the reference would point to an invalidated memory location, it refuses to compile the code.

Instead of crashing at runtime or reading "garbage" data, you get a clear error message: x does not live long enough.

Ensuring Memory Safety

By enforcing these rules, Rust ensures that if you have a reference to a value, that value is guaranteed to exist for as long as you are using the reference. You never have to worry about whether a pointer is still valid or if the underlying memory has been freed. The borrow checker turns these complex memory management hazards into compile-time errors, making your programs inherently safer.

Key Takeaway: The borrow checker prevents dangling references by ensuring that no reference can ever outlive the data it points to.