2 ms·
I don't know abou the memcpy part from Stack Overflow, but about the second part: It's UB to read from uninitialized data, and the thing about UB is that the c
by nextaccountic 6y ago
I don't know abou the memcpy part from Stack Overflow, but about the second part:
It's UB to read from uninitialized data, and the thing about UB is that the compiler doesn't need to be specially consistent about it. It doesn't need to select the same y for y ^ y, it might transform this into 0 ^ 0 or 10 ^ 5 or select any other arbitrary value for each instance of y in this expression. So the value of z can't be relied upon. even int z = 0*y; can't be relied to produce z equal to 0!
The compiler might even delete the whole code after int y = x; because after this line the code is UB. That's why the compiler might remove null-checks (and all code associated with it) done after you dereference a pointer, because since it's UB to follow a null pointer (the only way the program could be possibly correct is if the pointer were not null!), all further checks become dead code.
Also, the UB story in Rust is still being developed, but regarding memory representation it's expected to be the same as C. That's because LLVM is quite happy in doing such atrocious but spec-compliant optimizations.
Also, now that LLVM supports freeze as an operation (see links below), Rust might surface freeze to the programmer as a primitive low level operation, in order to control the propagation of uninitialized-ness and avoid doing UB when reading variables. It would be something like
let y = mem::freeze(x);
https://internals.rust-lang.org/t/taming-undefined-behavior-in-llvm/6183 https://internals.rust-lang.org/t/taming-undefined-behavior-...
https://www.reddit.com/r/rust/comments/gnx7y0/update_to_llvm_10_got_merged/ https://www.reddit.com/r/rust/comments/gnx7y0/update_to_llvm...