rust-lang / reference

The Rust Reference
https://doc.rust-lang.org/nightly/reference/
Apache License 2.0
1.22k stars 477 forks source link

Clarify note stating that reading uninitialized padding is permitted #1311

Open stevenengler opened 1 year ago

stevenengler commented 1 year ago

The reference says:

  • Producing an invalid value, even in private fields and locals. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation. The following values are invalid (at their respective type):
    • [...]
    • An integer (i*/u*), floating point value (f*), or raw pointer obtained from uninitialized memory, or uninitialized memory in a str.

and then later:

Note: Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside unions and in "padding" (the gaps between the fields/elements of a type).

What would be an example of reading uninitialized padding memory? Does this mean that reading uninitialized padding memory is an exception to the above rule (I'm guessing not, but I don't know how to interpret this note otherwise)? Would ptr::read::<u8>(ptr_to_padding) be considered "permitted"? Or does it only mean that ptr::read::<MaybeUninit<u8>>(ptr_to_padding) is "permitted"?

I think this note is unclear and should be reworded. The second sentence also starts with "In other words ...", but these two sentences seem like completely different ideas.

StripedMonkey commented 1 year ago

As far as I know this is in reference to the fact that copying/moving a struct may/will(?) read and copy the padding in the process of moving said struct despite the padding being uninitialized.