3 ms·
Um... what? That produces no exception on any architecture I know. In 2's complement, -INT_MIN == INT_MIN. It certainly can be represented in an integer, and
by ajross 15y ago
Um... what? That produces no exception on any architecture I know. In 2's complement, -INT_MIN == INT_MIN. It certainly can be represented in an integer, and it's perfectly legal to return -2147483648 from that division, and the machine in front of me certainly does.
Integer math is done modulo 2^n (with a -2^(n-1) offset for signed operations) on modern hardware. Overflow is part of the design. There are no exceptions defined for results that "can't be represented". Divide by zero aborts because the underlying mathematical concept doesn't exist; that's different from a mere overflow.
Obviously there can be bugs that can result from an overflow, but overflow bugs are hardly limited to INT_MIN.
- haberman 15y ago> Um... what? That produces no exception on any architecture I know. Have you tried actually compiling and running Tavis's test program with the given arguments? I did and it crashed on my Core i7 running on OS X. In gdb I get: (gdb) run -2147483648 -1 Starting program: /private/tmp/test3 -2147483648 -1 Reading symbols for shared libraries +. done Program received signal EXC_ARITHMETIC, Arithmetic exception. 0x0000000100000f23 in main () Hint: it won't work to just compile a program that does INT_MIN / -1 at compile-time, the compiler will do constant-folding that prevents an actual "idiv" instruction from being generated.
- ajross 15y agoOoh, my bad. Though I was actually smarter than that and made gcc (4.6.0, amd64) do the division. The problem is that "int a=0x80000000; printf("%d\n", a/-1);" when compiled without (!) optimization generates a NEG instruction, not an IDIV. That's not constant folding, that's strength reduction. And it's an optimization that I specifically told gcc not to do. Honestly I'd consider this a compiler bug. And of course NEG does what I expected and produces the 2's complementation negation of 0x8000000 (which is 0x80000000).
- barrkel 15y agoIntel x86 spec for idiv says Interrupt 0 is triggered if the quotient is too large to fit in the designated register. That would seem to be the case here.
- eggnet 15y agoNo, in two's complement: int_max + 1 == -int_min
- mturmon 15y agoOn PPC it does not produce an exception. Inspection of the assembler reveals, in part: cmpwi cr7,r0,0 beq cr7,L5 lwz r2,60(r30) lwz r0,56(r30) divw r2,r2,r0 ; ordinary integer divide stw r2,72(r30) ; store the quotient b L7 L5: li r0,0 ; else load 0 stw r0,72(r30) ; store the 0 The following thread has more about the reason PPC does not raise exceptions for these overflows: http://fixunix.com/embedded/341544-divide-zero-does-not-crash.html#post885372 http://fixunix.com/embedded/341544-divide-zero-does-not-cras... But they're only thinking about division by 0, not by -1.