Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Trouble with question in Brown Rust Book
I 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,
b
owns the Box after line 1.a
. When the function ends, the ownership isn't passed on. The Box is deallocated from the heap.b
is not the owner of anything. Thus I believe b2
does not receive ownership of any heap allocated Box.b2
nor b
own 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