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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14097924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:58:09  来源:igfitidea点击:

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

c++exceptiongdbarithmeticexception

提问by crognale

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:

我的Floating point exception (core dumped)C++ 程序出现错误,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;

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?

既然我知道我没有被零除,那么还有什么可能导致异常?

回答by crognale

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

所以我找出了导致问题的原因——算术异常可以通过除以零或有符号整数溢出来触发,这就是这里发生的情况。溢出时需要无符号整数环绕;有符号整数的行为未定义。

回答by PeterJ

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;

回答by DocKimbel

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 land rare 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.

为了计算这样的模表达式:-2147483648 % -1,需要一个除法,在这种情况下,这似乎是一个 32 位除法(我猜l并且r被定义为int)。这种除法的正确结果是2147483648,但该值不能用 32 位表示,因此会产生算术异常。