What is a dangling reference in Rust

A dangling reference in Rust is a reference to deallocated memory, prevented by the compiler's ownership and borrowing rules.

A dangling reference in Rust is a reference that points to memory that has already been deallocated, which the compiler prevents at compile time through its ownership and borrowing rules. Rust ensures that references are always valid by enforcing that a reference cannot outlive the data it points to, eliminating the possibility of accessing freed memory. Here is an example that would fail to compile if the reference were to outlive the data:

fn main() {
    let r;
    {
        let x = 5;
        r = &x; // Error: `x` will be dropped at the end of this scope, but `r` needs it to live longer
    }
    println!("r = {r}");
}