3 ms·
> I know rust considers uninitialized memory unsafe but I don't get why. All that really matters is that we initialize it to something. In the specific case of
by deathanatos 4y ago
> I know rust considers uninitialized memory unsafe but I don't get why. All that really matters is that we initialize it to something.
In the specific case of Rust, no, because not all values are valid. E.g., in the case of Rust, bool must be true (literally 1) or false (0); other values are UB. &str data must be valid UTF-8. Violating these invariants can cause other code that might depend on them to do odd things. E.g., an Option<bool> might rely on one of the other 254 values for the None variant[1], a UTF-8 decoder knowing the data "is" valid UTF-8 need not bound check continuation bytes leading to accesses outside the butter.
> Why can't we wait and let that be the first value that's actually meaningful instead of wasting time writing 0's?
Well, in Rust, see MaybeUninit (https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.h...). The docs page goes into the UB a bit, too (and names the above examples). So, you can … but it's often easier to just write a 0 or a known value & let the compiler make sure it's safe and optimize it out if it can.
[1]: Example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=caf8a9e13245a2a284dff59efc29e673 https://play.rust-lang.org/?version=stable&mode=debug&editio... — Option<bool> is 1 byte because the Option can take advantage of bool only using 2 out of 256 values of its byte. Cf. https://frehberg.com/2022/01/rust-memory-layout-optimization/ https://frehberg.com/2022/01/rust-memory-layout-optimization... and the first link in that.