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

前端 未结 5 1352
臣服心动
臣服心动 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:10

    As your code somewhat demonstrates, undefined behavior is almost always a condition of runtime state at the time the behavior is attempted. A slight modification of your code can make this painfully obvious:

    void causeUndefinedBehavior()
    {
       //any code that causes undefined behavior
       //every time it is run
       char* a = nullptr;
       *a;
    }
    
    
    int main()
    {
     srand(time(NULL));
     //code before call
     //...
     if (rand() % 973 == 0)
        causeUndefinedBehavior();
     //code after call
     //...
    }
    

    You could execute this a thousand times or more and never trip the UB execute-condition. that doesn't change the fact the function itself is clearly UB, but detecting it at compile time in context of the invoker is not trivial.

提交回复
热议问题