Attention people who think UB is fine
Recent discussions about undefined behavior in C have been met with an unusual perspective. Some believe that undefined behavior is perfectly fine and predictable, with the worst-case scenario being a segfault. However, this viewpoint overlooks the surprising consequences of certain actions.
One example is the execution of the explode() function, even though it was never called. Another instance involves dereferencing a null pointer, which leads to an attempt to access address zero. This can result in a segfault. The surprising aspect is that if the code changes to std::unreachable() being replaced with *ptr = 99, the generated program writes zero to memory address zero instead of the number 99, and then crashes due to an invalid instruction. The null pointer write, in this case, appears to be done to improve debugger error messages.
When the pointer is incremented by 10, the code behaves as someone might naively expect. This unexpected outcome highlights the unpredictable nature of undefined behavior. It's worth noting that compilers like GCC and Clang do not necessarily detect all instances of undefined behavior. They may stop emitting instructions for a function if they encounter a null pointer dereference, in an attempt to save binary size.
The halting problem makes it impossible for compilers to know in general cases whether specific code will ever be executed. This leads to various consequences when undefined behavior is triggered, including the infamous "nasal demons" scenario.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.