I have a code snippet 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()); }
which I compile with Visual C ++ 10 using /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
Note that there are two operations, โmodโ and โdiv,โ which can give UB if their second operand is zero at run time. In the emitted code, both are implemented using div codes that will cause a structured exception and program crash - the second operand is zero.
The first div before changing the volatile int variable, and the second after changing the volatile int .
So, if x is zero, the program crashes without changing the volatile int , but if x non-zero, and y is zero, the program changes the volatile int and then it will work.
Thus, depending on whether x or y zero, the program will exhibit different observed behavior.
Is it possible to alternate code with possible UB with code that affects the observed behavior?
c ++ compiler-optimization undefined-behavior visual-c ++
sharptooth Jul 18 '12 at 9:20 2012-07-18 09:20
source share