C++最早的未定义行为可以表现出来的是什么?

Ell*_*tch 10 c++ undefined-behavior

我知道未定义的行为可能会导致任何事情,这使得任何包含UB的程序都可能毫无意义.我想知道是否有任何方法可以确定程序中最早的一点,即未定义的行为可能会导致问题.这是一个例子来说明我的问题.

void causeUndefinedBehavior()
{
   //any code that causes undefined behavior
   //every time it is run
   char* a = nullptr;
   *a;
}


int main()
{
 //code before call
 //...
 causeUndefinedBehavior();
 //code after call
 //...
}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,可能引发未定义行为的可能时间(不一定表现出来)是:

  1. 何时causeUndefinedBehavior()编译.
  2. 何时main()编译.
  3. 在程序运行时.
  4. 当时causeUndefinedBehavior()执行.

或者,对于每个案例和每个实现,未定义的行为都会被完全不同?

另外,如果我注释掉causeUndefinedBehavior()调用的行,是否会消除UB,或者它是否仍然在程序中,因为编译了包含UB的代码?

Who*_*aig 5

正如您的代码在某种程度上表明的那样,未定义的行为几乎总是尝试该行为时运行时状态的一个条件。对代码稍加修改就会使这一点变得非常明显:

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
 //...
}
Run Code Online (Sandbox Code Playgroud)

您可以执行一千次或更多次,并且永远不会触发 UB 执行条件。这并没有改变函数本身显然是 UB 的事实,但在编译时在调用者的上下文中检测它并不是微不足道的。

  • 嗯,但是理论上编译器是否有可能决定,由于“causeUndefinedBehaviour()”会导致未定义的行为,因此永远不能在正确的程序中调用它,因此决定丢弃“if”是安全的。 (3认同)
  • @Mankarse 一个非常好的观点。将 main() 中的内容应用到 CauseUndefinedBehaviour() 中(将其称为 mayCauseUndefineBehavior())。也就是说,如果它也有条件地可能也有 UB...关键是没有*运行*你无法*知道*(不支持完整的抛出解释,据我所知,这是“运行”担心的)。 (2认同)