UB in Rust vs C
UB in Rust vs C
Posted Aug 14, 2024 21:56 UTC (Wed) by khim (subscriber, #9252)In reply to: UB in Rust vs C by mb
Parent article: Standards for use of unsafe Rust in the kernel
The devil is in details.
> If you construct a reference from a Null-pointer, it is insta-UB.Yes, but why?
> You don't even have to dereference it.But if you never dereference it then what harm could it do — would ask “we code for the hardware” guy. You may ask that it's needed to ensure that Option<&T> can be of the same size as &T, but the s/he would ask “what about references that are not ever used as Option<&T>?” and so on.
The truth is that list of UBs is, to some degree, always arbitrary. Rust tries not to include “really stupid” UBs. Like: have you even imagined that C++ has UBs (soon to be removed) in it's lexer! I mean: how deranged could you be to proclaim “if our compiler has difficulty breaking a source file into tokens, then it has carte blanche to produce whatever output it wants” ?
But still, not matter how hard you try it's always possible to invent some crazy construct that would violate UBs for seemingly good reasons (e.g. it's UB in Rust to use uninitialized memory for fun and profit even if hardware have no objections).
That means that without both sides agreeing to act in a good faith nothing could be achieved. Language developers have try to invent sane list of UBs that would be useful for writing real-world programs, but language users have to avoid UBs even in places where code with UB would be more efficient and even if they don't like these UBs!
Rust tries to keep the bargain “fair”, but many C/C++ developers feel that the right to violate that bargain is their unalienable right!
