Take a look at this piece of code
int main()
{
int i = 1U << 31; // assume this yields INT_MIN
volatile int x;
x = -1;
x = i / x; //dividing INT_MIN by -1 is UB
return 0;
}
It invokes undefined behavior on typical platform, but the "behavior" is quite different from what I expect -- it acts as if it were an infinite loop. I can think of a scene that it bites.
Of course undefined is undefined, but I have checked the output assembly, it is using a plain idiv
-- why does it not trap? For the sake of comparison, a divide by zero causes an immediate abort.
Using Windows 7 64 bit and MingW64
Can anyone explain this to me?
EDIT
I tried a few options, and the results were always the same.
Here is the assembly:
.file "a.c"
.def __main; .scl 2; .type 32; .endef
.section .text.startup,"x"
.p2align 4,,15
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
subq $56, %rsp
.seh_stackalloc 56
.seh_endprologue
call __main
movl $-1, 44(%rsp)
movl $-2147483648, %eax
movl 44(%rsp), %ecx
cltd
idivl %ecx
movl %eax, 44(%rsp)
xorl %eax, %eax
addq $56, %rsp
ret
.seh_endproc
.ident "GCC: (x86_64-posix-sjlj, built by strawberryperl.com project) 4.8.2"