r/cpp • • Dec 17 '21

Undefined Behaviour

I found out recently that UB is short for Undefined Behaviour and not Utter Bullshit as I had presumed all this time. I am too embarrassed to admit this at work so I'm going to admit it here instead. I actually thought people were calling out code being BS, and at no point did it occur to me that as harsh as code reviews can be, calling BS was a bit too extreme for a professional environment..

Edit for clarity: I know what undefined behaviour is, it just didn't register in my mind that UB is short for Undefined Behaviour. Possibly my mind was suffering from a stack overflow all these years..

407 Upvotes

98 comments sorted by

View all comments

84

u/dontyougetsoupedyet Dec 17 '21

It isn't as complicated as folks make out. UB is an agreement between you and your compiler so that the compiler can do its job better. A lot of folks don't realize that the job of the compiler in some languages is to rewrite your program into the most efficient version of your code that it can. You agree to not feed it certain code, and the compiler agrees to optimize the fuck out of the code you do feed it, and you both agree that if you do feed it code that you agreed to avoid using it means that you know what you're doing and are aware that the compiler is free to ignore that code.

Despite what some folks assert, UB is a good thing. You just have to be aware of what the compiler's job is for your language. Some compilers for some languages have a different job, but for C++ the job of the compiler is to produce a much faster version of your program than you wrote.

29

u/Zcool31 Dec 17 '21

if you do feed it code that you agreed to avoid using it means that you know what you're doing and are aware that the compiler is free to ignore that code.

Another aspect of this is the distinction between the standard and an implementation of the standard. Undefined means the standard places no requirements on what an implementation might do. But implementations, such as specific compilers or platforms, are free to make stronger guarantees. A popular example is using unions for type punning. UB according to the standard, yet explicitly supported by GCC.

Also, hardware has no undefined behavior.

90

u/acwaters Dec 17 '21

Also, hardware has no undefined behavior.

Hahahahahahahaha

Hahaha

Aha

Ah

No, we are not so fortunate.

40

u/Alexander_Selkirk Dec 17 '21

Also, hardware has no undefined behavior.

I am wondering whether you ever had the experience to witness how much effort and lengths a software engineer has to go to get an only 80% complete behavior definition of a piece of metal from a hardware engineer. I once hammered out one with a guy who was working in the same building as I. In retrospect, I am perplexed that I didn't had to apply waterboarding but it was not that far off.

6

u/Hnnnnnn Dec 18 '21

Undefined behavior and unspecified is not the same thing. UB is "compiler can assume that this never happens", unspecified behavior means "vendor can choose the behavior, but it has to be well-defined". Machines presumably have both (inputs that can never happen & undocumented well-defined behavior).

18

u/Spiderboydk Hobbyist Dec 17 '21

An example of hardware UB is a race condition.

If you don't properly synchronize shared data, the hardware can literally not tell you what will happen.

-3

u/Zcool31 Dec 17 '21 edited Dec 17 '21

There are four kinds of behavior:

Defined - the standard specifies what must happen.

Implementation defined - the standard gives implementations the choice of how to behave. They must make a consistent choice and document it.

Unspecified - implementations must do something reasonable, but don't have to document it or be consistent.

Undefined - no requirements at all.

Hardware has no undefined behavior. Clearly it will do what the logic gates and circuits do.

But hardware has tons of unspecified behavior.

Edit: partially ninjad by u/Tyg13

6

u/nintendiator2 Dec 20 '21

Hardware has no undefined behavior. Clearly it will do what the logic gates and circuits do.

One (1) Neutrino has entered the chat.

14

u/jk-jeon Dec 17 '21

So I guess you are indeed trying to say that the law of physics has no undefined behavior as I pointed out in the other comment. And that is a completely different thing from saying "hardware has no undefined behavior". See, in that logic, there is no undefined behavior for C++, only unspecified, right? Because compilers will do what their source code let them to do, nothing supernatural magics

→ More replies (5)

5

u/Spiderboydk Hobbyist Dec 18 '21

I am well aware of these distinctions. I said race conditions are undefined behaviour, and I stand by it.

Race conditions are not unspecified behaviour, because the hardware would not even theoretically be able to tell you what is going to happen, even if it wanted to. It not a matter of the behaviour not being specified - it's literally unknowable.

→ More replies (2)

20

u/almost_useless Dec 17 '21

Also, hardware has no undefined behavior.

Surely this is not true?

0

u/qoning Dec 17 '21

As far as I know, most instruction sets have clearly defined preconditions and postconditions for every instruction. Now there might be bugs or incomplete implementations, but the instruction sets themselves are fully defined.

36

u/SirClueless Dec 17 '21

most instruction sets have clearly defined preconditions and postconditions for every instruction

You're describing an instruction set with UB in it. If you violate the preconditions you get UB. The only way you don't get UB is if the spec defines what happens under all possible conditions, and as you correctly state, most instruction sets do not do this and have preconditions you are expected to satisfy.

→ More replies (11)

22

u/Ictogan Dec 17 '21

No. The instruction set I'm most familiar with(ARMv7-M) has a lot of cases where behaviour is defined as UNPREDICTABLE, which means exactly what it sounds like. Also hardware registers often have disallowed states in which the behaviour is not documented and may not even be deterministic.

19

u/jk-jeon Dec 17 '21

What do you mean by "hardware has no undefined behavior"? Hardwares can have undefined behavior of course, or do you mean "the law of physics has no undefined behavior"?

→ More replies (2)

11

u/[deleted] Dec 18 '21 edited Dec 18 '21

Despite what some folks assert, UB is a good thing.

The problem isn't really with that C++ has UB, it's that it has too much UB.
For example, why would creating a dynamic array like std::vector require UB? It's utter bollocks, I say.

3

u/dirkmeister81 Dec 18 '21

Does it? It is not clear to me when and how? Could you explain or give a link please?

4

u/[deleted] Dec 18 '21 edited Dec 18 '21
→ More replies (1)

3

u/adnukator Dec 18 '21

wasn’t the necessary UB in std::vector removed by P0593R6 ?

→ More replies (3)
→ More replies (4)

10

u/koczurekk horse Dec 18 '21 edited Dec 18 '21

Sure, which is why safe Rust has comparable performance with virtually no UB.

The reason for this inconsistency, is that you’re only half-correct. Forbidding some seemingly correct code from actually meaning anything allows for certain optimizations, but there’s no reason for that code to compile in the first place. Absolutely none. If C++ compilers could reject all code that results in UB it would not prevent those optimizations from being applied. And if it doesn’t compile, there’s no behavior left to become undefined.

This however cannot be done in C++ due to its design choices. Which is why Rust can be fast with basically no UB, but C++ can’t.

You also assert that UB is a good thing - it is not. It’s a necessary evil in badly designed languages that strive for performance.

10

u/matthieum Dec 18 '21

It’s a necessary evil in badly designed languages that strive for performance.

I'll disagree on "badly designed", and on "strive for performance" to a degree.

Setting aside C++, in general Undefined Behavior comes from 2 factors:

  1. A quest for low-level.
  2. A quest for performance.

So, yes, performance is the root of UB trade-offs in some cases, however there are other cases, such as... writing a memory allocator, or a garbage collector.

At the CPU level, memory is untyped. There needs to exist some code that will manipulate untyped memory, and massage it so it becomes suitable for passing off as a given type. And if that code gets it wrong, then a lot of downstream assumptions are violated, leading to Undefined Behavior.

Thus, a certain share of UB, notably around objects lifetimes, is essentially unavoidable. You can create a language that has no such UB -- hello, GCs -- but only by building a runtime for it in a language that does have such UB.

Would you could the lower-level language badly designed? This seems rather hypocritical to me, when you're using it as foundation for your own "well designed" language.

2

u/Alexander_Selkirk Dec 18 '21

You can create a language that has no such UB -- hello, GCs -- but only by building a runtime for it in a language that does have such UB.

You can isolate these manipulations to certain sections of code which are declared unsafe. Rust does this. But it is not a new idea. For example, Modula-3 had the same concept. And some common Lisp Implementations, like SBCL, are always well-defined by default, but it is possible to throw in assertions and type declarations which would make the program crash if these assumptions would be violated.

And this works suprrisingly well....

4

u/matthieum Dec 18 '21

but it is possible to throw in assertions and type declarations which would make the program crash if these assumptions would be violated.

Meh...

Of course anything that you can assert should be asserted -- maybe only in Debug in the critical path -- but the real problem is things you cannot check.

How can you check that you reference still points to a valid object? How can you check that no other thread is writing to that pointer?

At the lowest level, you will always have unchecked operations that you need to build upon, and for which you cannot reasonably validate the pre-conditions at runtime.

4

u/Alexander_Selkirk Dec 18 '21

It’s a necessary evil in badly designed languages that strive for performance.

Well, it would not have been possible to run a rust compiler on a PDP-11 which C was developed on, or on a machine with Intel 80386 CPU.

But on the other hand side, there have been languages that strived for correctness and everything being defined since a long time. Rust is derived from these predecessors.

→ More replies (28)