Is there any guarantee that code with UB should be available?

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?

+6
c ++ compiler-optimization undefined-behavior visual-c ++
Jul 18 '12 at 9:20
source share
2 answers

Yes, this implementation is allowed. See 1.9 / 5:

The corresponding implementation, executing a well-formed program, should provide the same observable behavior as one of the possible executions of the corresponding instance of an abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this international standard does not require the implementation of this program to be executed with this input (even with respect to operations preceding the first undefined operation).

+7
Jul 18 '12 at 9:37
source share

I think paragraph 1.9: 4 matters here:

Some other operations are described in this International Standard as not found (for example, eff ect attempts to modify the const object). [Note: This International Standard does not establish any requirements for the behavior of programs that contain undefined behavior. -end note]

As I understand it, this means that if the execution of the program ultimately leads to undefined behavior, then all the observed behavior of the program is undefined.

+5
Jul 18 '12 at 9:28
source share



All Articles