Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Exception in gdb, but I'm not dividing by zero?

I've been getting a Floating point exception (core dumped) error in my C++ program, and gdb shows that the problem is on a line that performs modulo division:

Program received signal SIGFPE, Arithmetic exception.
[Switching to Thread 0x7ffff6804700 (LWP 13931)]
0x00000000004023e8 in CompExp::eval (this=0x7fffec000e40, currVal=0)
    at exp.cpp:55
55              return (r==0) ? 0 : l % r;

The line guards against dividing by zero, and my backtrace shows the following:

#0  0x00000000004023e8 in CompExp::eval (this=0x7fffec000e40, currVal=0)
    at exp.cpp:55
        l = -2147483648
        r = -1

Since I know I'm not dividing by zero, what else could possibly be causing the exception?

like image 388
crognale Avatar asked Dec 31 '12 05:12

crognale


3 Answers

So I figured out what was causing the problem -- An arithmetic exception can be triggered either by dividing by zero, or overflow of a signed integer, which is what happened here. Unsigned integers are required to wrap around when overflowed; the behavior for signed integers is undefined.

like image 113
crognale Avatar answered Sep 20 '22 11:09

crognale


Change the code to the following to avoid trying to take the modulo of a negative number which is undefined:

return (r<=0) ? 0 : l % r;
like image 42
PeterJ Avatar answered Sep 20 '22 11:09

PeterJ


In order to calculate such modulo expression: -2147483648 % -1, a division is required, which in this case, seems to be a 32-bit division (I guess l and r are defined as int). The right result of such division would be 2147483648, but that value cannot be represented in 32-bit, so an arithmetic exception is produced.

like image 33
DocKimbel Avatar answered Sep 20 '22 11:09

DocKimbel