Undefined Behavior in C Can Make a Function You Never Called Run
Attention people who think UB is fine
A follow-up to an earlier post on undefined behavior in C, this time with compiler output to prove the skeptics wrong. Trigger UB in the same spot and GCC and Clang do wildly different things: one emits an uncalled function's code, another writes zero instead of 99 to address zero and then crashes on an invalid instruction, and a third case does exactly what the source says. The lesson: UB does anything.
I have now demonstrated three things UB can do, when UB was triggered in the same place: run whatever happens to be next in memory, store a random value at address zero and then deliberately crash, or do what one would naively expect.
- omoikane
The first example should have changed the heading to "C++ code" as opposed to "C code" due to the use of `std::unreachable()`. This matches the godbolt link.
Another alternative is to use `__builtin_unreachable()` (not standard, but available in GCC and Clang).
- charleslmunger
This is sort of true, except that behavior can be undefined in the standard but defined in your implementation. One of the best examples is -fwrapv, which makes signed integer overflow not UB. And Fil-C has no undefined behavior that I'm aware of. But most implementations target the standard and "define" what the standard doesn't to be "whatever I feel like, in service of implementation simplicity and performance". What matters is what your implementation guarantees, which should be a superset of what the standard does.
- Vaushite
"the definition of std::unreachable is: invokes undefined behaviour" does not mean that all undefined behaviour is equivalent to calling std::unreachable.
You saw it yourself: unreachable generates no code and suppresses the function epilog (duh - it's unreachable) but null deref generated a trap instruction in GCC. If you wanted a trap instruction, maybe this compiler reliably generates one from a hardcoded null deref.
- pestatije
UB - undefined behaviour
- johnea
Isn't a solution to simply not use unreachable()?