4 ms·
> While replacing the array of zeros by an array of uninitialised values may work in specific circumstances, the code is unsound. Change to the compiler, its op
by School-Cotton 2y ago
> While replacing the array of zeros by an array of uninitialised values may work in specific circumstances, the code is unsound. Change to the compiler, its options, modification of unrelated parts of the code or using the function for a different Read trait implementation may break the program in unpredictable ways.
Why? It seems the only thing on that list that will cause UB is using the function with a different reader (one that inspects the uninitialized bytes). Why would any of the other listed possible changes break it?
- GrantMoyer 2y agoIn Rust, creating a reference to uninitialized data is undefined behavior, even if you don't access the data through it[1]. The optimizer assumes all references are intialized. [1]: https://doc.rust-lang.org/std/ptr/#pointer-to-reference-conversion https://doc.rust-lang.org/std/ptr/#pointer-to-reference-conv...
- GrantMoyer 2y agoFollow up to my earlier comment; The docs say creating a reference to uninitialized memory is undefined behavior, but I couldn't think of any cases where it would go wrong if the data is never actually accessed. It turns out that's because there currently aren't any. See comment [1] and the threads linked there. Rust calls references to uninitialized memory undefined behavior because it wants to reserve the right to implement some kinds of optimizations using that fact in the future, however currently no optimizations do, and in fact the standard library depends on the compiler being well behaved here. It's possible at some point in the future some optimization will be added which would cause problems for references to uninitialized memory, but it seems more likely that the requirements on references will eventually be relaxed instead. [1]: https://github.com/rust-lang/rust/issues/119241#issuecomment-1868235132 https://github.com/rust-lang/rust/issues/119241#issuecomment...