C++ What is the earliest undefined behavior can manifest itself?

前端 未结 5 1353
臣服心动
臣服心动 2021-01-17 19:48

I\'m aware that undefined behavior can potentially cause anything, which makes any program containing UB potentially meaningless. I was wondering if there is any way to iden

5条回答
  •  臣服心动
    2021-01-17 20:06

    I think it depends on the type of undefined behavior. Things that would affect something like structure offsets could cause undefined behavior, which would show up any time code that touches that structure is executed.

    In general, however, most undefined behavior happens at run time, meaning only if that code is executed will the undefined behavior occur.

    For example, an attempt to modify a string literal has undefined behavior:

    char* str = "StackOverflow";
    memcpy(str+5, "Exchange", 8);    // undefined behavior
    

    This "undefined behavior" will not take place until the memcpy executes. It will still compile into perfectly sane code.

    Another example is omitting the return from a function with a non-void return type:

    int foo() {
        // no return statement -> undefined behavior.
    }
    

    Here, it is at the point at which foo returns that the undefined behavior occurs. (In this case, on x86, whatever happened to be in the eax register is the resultant return value of the function.)

    Many of these scenarios can be identified by enabling the a higher level of compiler error reporting (eg. -Wall on GCC.)

提交回复
热议问题