Search code examples
c++xcodeinteger-divisionsecure-coding

Runtime error dividing by -1


I don't doubt the need to check for division by zero. I've never heard of checking for division by negative one though!

if( *y == 0 )
    return 0; //undefined
else
    return *x / *y;

x, y are pointers to int32_t, I include this detail in case of relevance.

At runtime, if *x==0x80000000, *y==0xffffffff, I get the error (in Xcode):

EXC_ARITHMETIC (code=EXC_I386_DIV, subcode=0x0)

All I can find online is suggestions that it is division by zero, but as you can see from the check above, and I can see from the debug window, that is not the case here.

What does the error mean, and how can I fix it?


Solution

  • 2's complement representation is asymmetric: there is one more negative number than positive number, and that negative number has no positive counterpart. Consequently, negating MIN_INT is an integer overflow (where MIN_INT is the value whose only 1-bit is the sign bit, 0x80000000 for 32-bit integers).

    MIN_INT / -1 is, therefore, also an arithmetic overflow. Unlike overflow from subtraction (which is rarely checked), overflow when dividing can cause a trap, and apparently that's what is happening in your case.

    And, yes, technically speaking you should check for the MIN_INT / -1 overflow case before dividing, because the result is undefined.

    Note: In the common case of Intel x64 architecture, division overflow does trap, exactly the same as division by 0. Confusingly, the corresponding Posix signal is SIGFPE which is normally thought of as "Floating Point Exception", although there is no floating point in sight. The current Posix standard actually glosses SIGFPE as meaning "Erroneous Arithmetic Operation".