2012.04.06 - "undefined behavior" IS bad

among projects i worked on, there were cases, where undefined behavior was exploited, to achieve something useful. just to mention one case, when memory was allocated with new MyClass and freed… using free(void*). this was (still is?) done in the main messaging framework of the million-line project. for compiler version in use, it happened to work, as long as MyClass had POD-only members1).

i was always against such a hacks and promoted solutions that would not require it. in practice most of the times the answer was “it's working so don't touch it”. very ignorant approach at least…

when something is UB, you should see big red sign, that says: “if you cross this line ANYTHING can happen”. and so yesterday i came across a guy on the usenet, posting that his few-lines program does not work when compiled with optimizations on GCC 4.6. here it is:

everything works fine – program executes and prints the result on the screen. adding optimizations, however causes program to loop forever. namely, if compiled with:

g++ -Wall x.cpp -O3

program never ends. what is the problem with this code? it uses UB of overflowing signed integer. adding -fno-strict-overflow (i.e. of-the-standard extension, making signed integer overflows defined) solves problem – compiler computes value in compile-time and puts a constant value in the code.

using the wrong side of force is asking for a trouble. if you do so, sooner or later you'll bounce from the wall, spend hours (or days) debugging just to find out you're not spec-compliant and having to fix code, that should have been written the right way from the very beginning. is it worth it?

btw: GCC 4.7 gives the same results as 4.6, while GCC 4.5 and Clang++ 3.0 gives “expected” results. unless you're an oracle, forget about using UBs!.