Compiler Undefined Behavior
The cluster discusses how compilers optimize code assuming no undefined behavior (UB), resulting in surprising or broken outputs when UB occurs, with debates on whether this is the programmer's fault, beneficial for performance, or if compilers should instead error on detected UB.
Activity Over Time
Top Contributors
Keywords
Sample Comments
Yes, compilers take advantage of undefined behavior.
It's not that the compiler does not agree. It's that it operates under the assumption that there is no UB. If the compiler knew for sure that there is going to be UB (which happens at runtime, not compile time) of course it would tell. (Surely in some cases, the compiler needs to be improved to see UB that can be detected statically without much effort).And if you don't request heavy optimization, what happens when UB occurs is likely just what you expected to happen on that pa
From the compiler's PoV this is buggy code so it's better to make it predictably wrong rather than unboundedly incorrect (=security issues) or predictably correct (=people rely on UB).
This is not a problem with the committee and is not a problem with compiler writers. The committee is only marking certain behaviors as UB. Compilers can do what they think is more sensible in these situations. And compiler writers are not forcing you to accept these extreme optimizations. You always have the option of disabling optimizations and accept that your code has bugs (UB). You just need to test the code you write under different compiler settings, similarly to how you test code in diff
because a lot of users here think that a compiler somehow detects undefined behavior, then emits wacky code just to spite them.
Compilers are afraid to optimize around possible UB, even though they can.
Security bugs caused by compilers optimizing based on Undefined Behavior in your code are 100% your fault, 0% the compiler's fault.
Doesn't matter anymore, Clang and GCC will both make any and all optimizations they can find by assuming you will never hit UB, including just erasing all UB code. You can dislike it, but that's just the reality now, and ignoring it won't make it go away. The only way to change it would be a change in the standard.
Any optimization that causes undefined behavior is bugged – please report them to your compiler's developers.
Yes, but the way these optimizations work, is not that they detect UB and optimize accordingly, instead they optimize assuming no UB. There is nothing to report at compile time.