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)
根据我的理解,可能引发未定义行为的可能时间(不一定表现出来)是:
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
//...
}
Run Code Online (Sandbox Code Playgroud)
您可以执行一千次或更多次,并且永远不会触发 UB 执行条件。这并没有改变函数本身显然是 UB 的事实,但在编译时在调用者的上下文中检测它并不是微不足道的。
| 归档时间: |
|
| 查看次数: |
316 次 |
| 最近记录: |