top | item 36001698

(no title)

wanttocomment | 2 years ago

All rust code is UB because there is no spec. I don't mean this as a knock against rust, but against UB fear.

discuss

order

nicoburns|2 years ago

That is not what UB means. Undefined Behaviour is behaviour that the compiler is allowed to assume will never happen, and which can consequently cause miscompilations due to optimisation passes gone wrong if it does in fact occur in the source code.

It's true that Rust does not have a written specification that clearly delineates what is and isn't UB in a single place. But:

1. UB is impossible in safe code (modulo bugs in unsafe code)

2. There are resources such as the Rustinomicon (https://doc.rust-lang.org/nomicon/) that provide a detailed guide on what is and isn't allowed in unsafe code.

In practice, it's much easier to avoid UB in Rust than it is in C++.

mr_00ff00|2 years ago

I am familiar with UB as a result of memory unsafety, but the way it is talked about it sounds like the only ways to ever cause UB is with memory unsafety.

Based on that definition it feels like it should be possible to have UB outside of memory violations, is there really no UB in languages like Java/Haskell/Go?

ynik|2 years ago

But Rust has kind of a spec: https://doc.rust-lang.org/reference/ Sure, it's not as well-specified as C++; so one could say it's "not a real spec".

But C++ also isn't perfect, there are plenty of programs for which no two compiler developers can agree on whether they have UB. The C++ spec language is just too ambiguous and underspecified in several areas.

If you want to be sure, you need an actual machine-checkable formal specification. Neither C++ nor Rust have that.

In the end, what really matter is the contract between the programmer and the compiler: are compilers allowed to break a program in weird ways because the programmer forgot about one of the arcane rules in the spec? For C++ and unsafe Rust, the answer is yes (we don't know how to build optimizing compilers for low-level languages otherwise). But for safe Rust, the answer is no. That's a big deal.