At what point in the loop does integer overflow become undefined behavior?

后端 未结 12 2265
南方客
南方客 2020-12-07 18:12

This is an example to illustrate my question which involves some much more complicated code that I can\'t post here.

#include 
int main()
{
           


        
12条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 18:41

    First, let me correct the title of this question:

    Undefined Behavior is not (specifically) of the realm of execution.

    Undefined Behavior affects all steps: compiling, linking, loading and executing.

    Some examples to cement this, bear in mind that no section is exhaustive:

    • the compiler can assume that portions of code that contain Undefined Behavior are never executed, and thus assume the execution paths that would lead to them are dead code. See What every C programmer should know about undefined behavior by none other than Chris Lattner.
    • the linker can assume that in the presence of multiple definitions of a weak symbol (recognized by name), all definitions are identical thanks to the One Definition Rule
    • the loader (in case you use dynamic libraries) can assume the same, thus picking the first symbol it finds; this is usually (ab)used for intercepting calls using LD_PRELOAD tricks on Unixes
    • the execution might fail (SIGSEV) should you use dangling pointers

    This is what is so scary about Undefined Behavior: it is nigh impossible to predict, ahead of time, what exact behavior will occur, and this prediction has to be revisited at each update of the toolchain, underlying OS, ...


    I recommend watching this video by Michael Spencer (LLVM Developer): CppCon 2016: My Little Optimizer: Undefined Behavior is Magic.

提交回复
热议问题