BrainSteel
BrainSteel

Reputation: 669

EXC_ARITHMETIC Error With Nonzero Denominator - XCode

Usually, when I get an EXC_ARITHMETIC error, it means I divided by zero, which makes sense to me. However, this time I have no idea what is going on. Here is a function that is being called rather frequently:

GP_TYPE GP_NodeFunction_Divide(GP_Node* node, GP_Mem* mem, void* data){

    /* These are just normal function calls.
       I can say with some certainty they are not misbehaving. */
    GP_TYPE denom = GP_Call(node->next[1], mem, data);
    GP_TYPE num = GP_Call(node->next[0], mem, data);

    if (denom) {
        /* denom != 0, right? */
        return num / denom; /* Crash! EXC_ARITHMETIC */
    }

    else return 1e12;
}

My program runs for several minutes with no incident, presumably calling this functions hundreds of thousands of times, but will still crash here occasionally.

GP_TYPE is defined as follows:

#ifdef GP_USE_DOUBLE
#define GP_TYPE double
#else
#define GP_TYPE int
#endif

GP_USE_DOUBLE is NOT defined.

I've been compiling with -O0, and XCode's debug window holds this information at the crash site:

...
num = (int)-2147483648
denom = (int)-1
...

This information is consistent. Every time this function crashes, the values of num and denom are the same.

I tried to specifically type num / denom into the debug window as an expression, and XCode promptly crashed (Which, I suppose, is not the weirdest thing about this bug).

I can also navigate the debug window to observe the GP_Node* node, and it has been a valid pointer, with valid elements, every time it crashes.

Is XCode's debug window bugged? (I've just recently updated to XCode 6.3.2)

Is denom secretly 0? Is this even possible?

Is there another way to get an EXC_ARITHMETIC from a division of ints?

What is going on?

Upvotes: 1

Views: 61

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49803

Your num happens to be the most negative number that can be represented by a signed 32-bit variable (assuming 2's complement); unfortunately for you, the most positive number that can be so represented is 2147483647 - one less than -2147483648/-1.

Upvotes: 2

Related Questions