Null reference as insta-UB
Null reference as insta-UB
Posted Aug 16, 2024 13:29 UTC (Fri) by farnz (subscriber, #17727)In reply to: UB in Rust vs C by intelfx
Parent article: Standards for use of unsafe Rust in the kernel
There's a theoretical reason, and a practical reason.
First, the theoretical reason: a reference has a validity constraint that it always, unconditionally, refers to a valid place. If you permit a reference to be "null", you now have to change the validity constraint to say that the reference either refers to a valid place, or is null; this is Hoare's "billion dollar mistake". There's a whole pile of things that pile up behind this change; it's not a trivial thing to do, since it affects the semantics of the entire language.
The practical reason is around optimization: if a reference must point to a valid place, then it's always OK to access the place it points to; that, in turn, means that you can write clear code, and have the compiler optimize it to the best code. It can, for example, change a conditional read of a reference to an unconditional read and a conditional use at all the places you had a conditional read, without having to consider the possibility that the conditional use was protecting against the reference being null. And because the compiler is aware of the memory model, it can issue the read much earlier, knowing that there are no memory accesses later in the function that can affect either where the reference points to, or what the value read can be.
