C ++最早可以显示的未定义行为是什么? [英] C++ What is the earliest undefined behavior can manifest itself?

查看:61
本文介绍了C ++最早可以显示的未定义行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 identify the earliest point in a program that undefined behavior could cause problems. Here is an example to illustrate my question.

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
 //...
}

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

From my understanding, the possible times undefined behavior could be evoked (not necessarily manifested) are:

  1. 编译 causeUndefinedBehavior()时.
  2. 编译 main()时.
  3. 程序运行时.
  4. 执行 causeUndefinedBehavior()时.
  1. When causeUndefinedBehavior() is compiled.
  2. When main() is compiled.
  3. At the time the program is run.
  4. At the time causeUndefinedBehavior() is executed.

或者对于每种情况和每种实现,引发未定义行为的观点是完全不同的吗?

Or is the point where undefined behavior is evoked completely different for every case and every implementation?

此外,如果我在调用 causeUndefinedBehavior()的行中注释掉,会消除UB,还是因为包含UB的代码已被编译,它仍在程序中?

In addition, if I commented out the line where causeUndefinedBehavior() is called, would that eliminate the UB, or would it still be in the program since code containing UB was compiled?

推荐答案

正如您的代码在某种程度上说明的那样,未定义的行为在尝试执行行为时几乎总是运行时状态的条件.稍微修改一下代码就可以使这一点很明显:

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
 //...
}

您可以执行此操作一千次或更多,而永远不会触发UB执行条件.但这并不会改变函数本身显然是UB的事实,但是在调用程序的上下文中在编译时检测并不是很简单.

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.

这篇关于C ++最早可以显示的未定义行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆