本文介绍了是否有任何保证是否与UB的代码应该可达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码段:

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 并获得此反汇编:

which I compile with Visual C++ 10 with /O2 and get this disassembly:

00403940  push        ebx
00403941  push        esi
   276:     function(rand(), 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 操作码来实现,这将触发结构化异常,程序崩溃的第二个操作数为零。

Note that there're two operations - "mod" and "div" that could possibly yield UB if their second operand is zero at runtime. In the emitted code both are implemented with div opcodes that will trigger a structured exception and crash the program is the second operand is zero.

第一个 div 在修改 volatile int 变量之前, code> volatile int 被修改。

The first div is before the volatile int variable is modified, but the second one is after volatile int is modified.

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

So if x is zero the program crashes without modifying the volatile int but if x is nonzero and y is zero then the program modifies volatile int and then crashes.

c $ c> x 或 y 为零,程序将显示不同的可观察行为。

So depending on whether x or y are zero the program will exhibit different observable behavior.

是否可能的代码与可能的UB代码交织,影响可观察的行为?

Is such interleaving of code with possible UB with code that affects observable behavior allowed?

推荐答案

见1.9 / 5:

这篇关于是否有任何保证是否与UB的代码应该可达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:20