3 ms·
> Reads of uninitialized memory is unsafe full stop. That’s literally what Rust’s memory safety is about. If you give that up you’re not in safe land and you ca
by lmm 2y ago
> Reads of uninitialized memory is unsafe full stop. That’s literally what Rust’s memory safety is about. If you give that up you’re not in safe land and you can always use unsafe & all the risks that come with that to try to write more optimal code / abstractions.
Reading uninitialized (but correctly owned) memory is not inherently unsafe. It has strange (and mostly useless) semantics, but it's not a safety issue. E.g. something like the OpenSSL key generation that Debian broke - [uninitialised buffer] ^= [generated random values] - is safe, and afterwards you can read from that buffer and get (safe, real, stable) values.
- vlovich123 2y agoI’m not sure what point you’re arguing. C and C++ treat uninitialized reads as UB, full stop. Any C/C++ compiler can do whatever it wants if it realizes that’s the case. Rust is no different, it’s just that it makes it a compile error in “safe” mode and forces you to annotate it with unsafe to be explicit it’s intentional (while still following the rules mind you - accessing uninitialized memory is still UB even in unsafe rust and doing so gives the compiler freedom to break your code)
- lmm 2y ago> C and C++ treat uninitialized reads as UB, full stop. Not true; if it's an object that has its address taken, of a type that does not have a trap representation, then reading it results in an unspecified value and is not UB. Which aligns with what one might naively expect to happen.
- vlovich123 2y agoThis is true of Rust as well since it has a very similar memory model. You just have to explicitly tell the compiler you know what you’re doing in Rust through the unsafe keyword.
- lmm 2y agoSo reading an uninitialised u8 is not UB? I found the Rust documentation pretty unclear, u8 does not have a "restricted set of valid values" which suggests it should be ok, but the documentation also says "the only cases in which reading uninitialized memory is permitted are inside unions and in “padding” (the gaps between the fields of a type)".