Hacker News new | ask | show | jobs
by nicoburns 1129 days 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++.

1 comments

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?

You can have it for reasons other than memory safety, for example signed integer overflow is UB in C and C++ (but not in Rust). However, higher level languages typically go to great lengths to avoid it. For example, in Java you will get a NullPointerException rather a null pointer actually being dereferenced, which immediately rules out any UB due to a pointer being dereferenced where doing so is not allowed.
Wow signed overflow is UB? I would have assumed it was defined, it just allows overflow.

And I am assuming something like the NullPointerException comes with a huge performance hit? Otherwise I assume every systems language would do something similar.

I cannot think of a useful way to define signed overflow. I can make it do something, but at the end of the day no matter how you define it, if it happens in the real world your program has a bug.

Since we can be sure if it ever happens your code has a bug, making it undefined is a good thing: the compiler can then assume it doesn't happen and so back track to prove some other things can't happen and so make your program run a little faster.

I'd much rather have a bug in my program than UB. At least the bug is easy to track down and fix, and is limited in scope to the line of code that contains the error.
You sacrifice speedy code for this case that probably won't even happen and so you probably won't have to debug anyway. Is it really worth it?
> Wow signed overflow is UB? I would have assumed it was defined, it just allows overflow.

Presumably it's not defined because the behaviour depends on the signedness representation.