我知道未定义的行为可能会导致任何事情,这使得任何包含 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
//...
}
根据我的理解,未定义行为可能被引发(不一定表现出来)的时间是:
- 当
causeUndefinedBehavior()
被编译时。 - 当
main()
被编译时。 - 程序运行时。
- 在执行
causeUndefinedBehavior()
时。
或者对于每种情况和每种实现,未定义行为的诱发点是完全不同的吗?
此外,如果我注释掉调用 causeUndefinedBehavior()
的行,是否会消除 UB,或者它是否仍然存在于程序中,因为包含 UB 的代码已被编译?
最佳答案
正如您的代码所展示的那样,未定义的行为几乎始终是尝试行为时的运行时状态 的条件。对您的代码稍作修改可以使这一点变得非常明显:
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 的事实,但是在编译时在调用程序的上下文中检测它不是微不足道的。
关于C++ 最早可以表现出来的未定义行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13114459/