gdb中的算术异常,但我没有除以零?

时间:2012-12-31 05:44:40

标签: c++ exception gdb arithmeticexception

我的C ++程序中出现Floating point exception (core dumped)错误,gdb显示问题出现在执行模数除法的行上:

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;

该线防止零除,我的回溯显示以下内容:

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

因为我知道我没有除以零,还有什么可能导致异常呢?

3 个答案:

答案 0 :(得分:7)

所以我弄清楚是什么导致了这个问题 - 算术异常可以通过除以零或者 signed 整数的溢出来触发,这就是这里发生的事情。溢出时需要无符号整数包围;有符号整数的行为是未定义的。

答案 1 :(得分:3)

将代码更改为以下代码,以避免尝试取未定义的负数的模数:

return (r<=0) ? 0 : l % r;

答案 2 :(得分:2)

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.