cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
503 stars 82 forks source link

Ownership Inventory #1 Q2 is wrong about UB #163

Open fee1-dead opened 4 months ago

fee1-dead commented 4 months ago

URL to the section(s) of the book with this problem:

https://rust-book.cs.brown.edu/ch06-04-inventory.html

Description of the problem:

Per https://doc.rust-lang.org/nomicon/what-unsafe-does.html, Undefined Behavior arises from producing an invalid value, which means the let s = make_separator(""); choice would also cause UB. We should set the record straight and correctly tell people that producing invalid values causes UBs even though the code might be harmless when you run it. A reference can't ever be dangling, null, or point to an invalid value. That's the contract of the type. If you ever violate the contract (even without reading the value from the reference) bad things are allowed to happen.

Suggested fix:

Make it a correct option, or remove that as a distractor.

Nilstrieb commented 4 months ago

producing a value

Or to be more precise, it arises from doing a typed copy of an invalid value. The assignment to s is a typed copy, and references have a validity invariant that they point to a valid allocation.

It's up to debate whether the referent needs to be valid, so a reference to uninitialized memory might or might not be UB.

willcrichton commented 1 week ago

This is the same issue reported in #33. I've gone back and forth on this issue (see the linked thread), but given my principle of being consistent with Miri, I've decided to remove the distractor.