I can not understand Dangling References

This morning, I read a book from the library that mentions dangling references, but I cannot understand what dangling references mean.

Here is the code snippet related to dangling references:

fn main() {
    let reference_to_nothing=dangle();
}
fn dangle()->&String{
    let s=String::from("hello");
    &s
}

A dangling reference is a reference to something that no longer exists at the referenced location (because it has been deallocated, for example). A simple case, as in your example, would be taking a reference to something on the stack that then goes out of scope. In particular, s goes out of scope at the end of the function, so the reference to it that gets returned from the function is dangling. Rust won't actually let you write such a function, because it checks that all references don't outlive the thing they reference.

4 Likes

Wikipedia has an article on the topic, written primarily from a C point-of-view.

1 Like

I find it easy to understand, and it is better than the Chinese Rust book from the library. Thank you very much for the help.

1 Like

I read the Wikipedia page about dangling references, and while it was not easy for me to understand initially, after reading it three times, I was able to comprehend it. Thank you very much.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.