UB in Rust vs C
UB in Rust vs C
Posted Aug 14, 2024 19:39 UTC (Wed) by ralfj (subscriber, #172874)Parent article: Standards for use of unsafe Rust in the kernel
This quote had me very surprised, since in general C and C++ also treat UB as something that is totally forbidden.
Turns out there is a bit more context in the actual patch:
> "In C one might rely on the compiler implementation to ensure correct code generation, but that is not the case for Rust."
So (I think) what this refers to is that a C compiler can explicitly document that it chooses to turn some UB into well-defined behavior. This should only be relied upon by the programmer if it is documented, since if the compiler just "happens to" do something well-defined for UB, that may change with future compiler versions. Rust only has a single compiler, and everything we document as UB is indeed "UB and we mean it"; there are no guarantees provided by the compiler for any of the documented UB. If there is behavior we think we can define without undue impact on optimizations, we will just make it well-defined, and thus reduce the amount of UB programmers have to worry about. (See https://github.com/rust-lang/rust/issues/117945 for a recent case of that.)
Even if/when there will be multiple Rust compilers, there is still a general preference to not have such compiler-specific differences. It would be quite bad if some libraries were well-defined with one Rust compiler but UB with another. So we are asking everyone that embarks on alternative Rust implementations to treat UB the same way rustc does, and to my knowledge the gcc-rs folks are indeed planning to exactly match rustc in terms of what is and is not UB.
