Reputation: 21
fn dangle() -> &String { // dangle returns a reference to a String
let s = String::from("hello"); // s is a new String
&s // we return a reference to the String, s
}
Going through rust book and learning about ownership, How does returning a reference to a String make it a dangling pointer?
Upvotes: 2
Views: 767
Reputation: 21
The string you're referencing lives inside the function (only). That means, that the management code to allocate and deallocate memory for this string will be put into this function by the compiler. Therefore the compiler has to deallocate the memory for s before returning to the caller. However, &s
would now reference a deallocated item, that is a dangling pointer.
Upvotes: 2