Trouble with question in Brown Rust Book
⚓ Rust 📅 2025-08-21 👤 surdeus 👁️ 12I have a question from the Rust book. I'm getting really wrapped around the axle on this one.
Chapter 4.1 (Ownership) has this question at the end:
Question 4
Say we have a function that moves a box, like this:
fn move_a_box(b: Box<i32>) {
// This space intentionally left blank
}
Below are four snippets which are rejected by the Rust compiler. Imagine that Rust instead allowed these snippets to compile and run. Select each snippet that would cause undefined behavior, or select "None of these snippets" if none of these snippets would cause undefined behavior.
Snippet:
1. let b = Box::new(0);
2. move_a_box(b);
3. let b2 = b;
I actually only care about 1 of the 4 snippets, and I omitted the other 3.
My analysis: In the above snippet,
- The variable
bowns the Box after line 1. - In line 2, ownership of the Box is moved to function's parameter
a. When the function ends, the ownership isn't passed on. The Box is deallocated from the heap. - In line 3,
bis not the owner of anything. Thus I believeb2does not receive ownership of any heap allocated Box. - The snippet ends, and the free is performed on any variables that own heap memory. But neither
b2norbown any heap memory at this point.
Where is the undefined behavior in this? I believe there isn't a free-already-freed memory op, because no variables own any heap memory.
3 posts - 3 participants
🏷️ Rust_feed