c – 是否可以保证UB代码是否可以访问?

前端之家收集整理的这篇文章主要介绍了c – 是否可以保证UB代码是否可以访问?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个代码片段 from here
volatile int volatileInt;
int usualInt;

void function (unsigned x,unsigned y,unsigned z)
{
    volatileInt = 0;
    usualInt = (x % y) / z;
}

int main()
{
    function(rand(),rand(),rand());
}

我用Visual C 10用/ O2编译并得到这个反汇编:

00403940  push        ebx  
00403941  push        esi  
   276:     function(rand(),rand());
00403942  mov         esi,dword ptr [__imp__rand (4050C0h)]  
00403948  push        edi  
00403949  call        esi  
0040394B  mov         edi,eax  
0040394D  call        esi  
0040394F  mov         ebx,eax  
00403951  call        esi  
00403953  xor         edx,edx  
00403955  div         eax,ebx  <<<< possible UB
00403957  mov         dword ptr [volatileInt (4074D0h)],0  
00403961  mov         eax,edx  
00403963  xor         edx,edx  
00403965  div         eax,edi  <<<< possible UB
00403967  pop         edi  
00403968  pop         esi  
00403969  pop         ebx  
0040396A  mov         dword ptr [usualInt (4074CCh)],eax  
   277:     return 0;
0040396F  xor         eax,eax
00403971  ret

请注意,有两个操作 – “mod”和“div”,如果第二个操作数在运行时为零,则可能产生UB.在发出的代码中,两者都使用div操作码实现,这将触发结构化异常并且程序崩溃,第二个操作数为零.

第一个div是在修改volatile int变量之前,但第二个div是在修改volatile int之后.

因此,如果x为零,程序崩溃而不修改volatile int,但如果x为非零且y为零,则程序修改volatile int然后崩溃.

因此,根据x或y是否为零,程序将表现出不同的可观察行为.

是否允许使用可能影响可观察行为的代码代码与可能的UB进行交错?

解决方法

是的,允许这种实现.见1.9 / 5:

A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However,if any such execution contains an undefined operation,this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

@H_403_27@

猜你在找的C&C++相关文章