(no title)
electrograv | 9 months ago
UB doesn’t occupy the author’s mind when writing C, when it really should. This kind of lazy attitude to memory safety is precisely why so much C code is notoriously riddled with memory bugs and security vulnerabilities.
mk12|9 months ago
Arnavion|9 months ago
It's not as painless as it could be though, because many of the MaybeUninit<T> -> T conversion fns are unstable. Eg the code in TFA needs `&mut [MaybeUninit<T>] -> &mut [T]` but `[T]::assume_init_mut()` is unstable. But reimplementing them is just a matter of copying the libstd impl, that in turn is usually just a straightforward reinterpret-cast one-liner.
codeflo|9 months ago
There are two actual differences in this regard: C pointers are more ergonomic than Rust pointers. And Rust has an additional feature called references, which enable a lot more aggressive compiler optimizations, but which have the restriction that you can’t have a reference to uninitialized memory.
nemothekid|9 months ago
uecker|9 months ago
usefulcat|9 months ago
It sounds like the more difficult problem here has to do with explaining to the compiler that read() is not being used unsafely.
o11c|9 months ago
Most other UBs related to datums that you think you can do something with.
lhecker|9 months ago
If I write the equivalent code in Rust I may write
The problem is now obvious to me, but at least my intention is clear: "Come here! Give me your uninitialized arrays! I don't care!". But this is not the end of the problem, because writing this code is theoretically unsafe. If you have a `[u8]` slice for `out` you have to convert it to `[MaybeUninit<u8>]`, but then the function could theoretically write uninitialized data and that's UB isn't it? So now I have to think about this problem and write this instead: ...and that will also be unsafe, because now I have to convert my actual `[MaybeUninit<u8>]` buffer (for file writes) to `[u8]` for calls to this API.Long story short, this is a problem that occupies my mind when writing in Rust, but not in C. That doesn't mean that C's many unsafeties don't worry me, it just means that this _particular_ problem type described above doesn't come up as an issue in C code that I write.
Edit: Also, what usefulcat said.
ninkendo|9 months ago
Something like:
(Honest question, actually… because the above may be impossible to write and I’m on my phone and can’t try it.)Edit: it works: https://play.rust-lang.org/?version=stable&mode=debug&editio...