
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 UB00403957 mov DWord ptr [volatileInt (4074D0h)],0 00403961 mov eax,edx 00403963 xor edx,edx 00403965 div eax,edi <<<< possible UB00403967 pop edi 00403968 pop esi 00403969 pop ebx 0040396A mov DWord ptr [usualint (4074CCh)],eax 277: return 0;0040396F xor eax,eax00403971 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).
以上是内存溢出为你收集整理的c – 是否可以保证UB代码是否可以访问?全部内容,希望文章能够帮你解决c – 是否可以保证UB代码是否可以访问?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)