简体   繁体   English

C ++中的SIGFPE方向错误

[英]SIGFPE misdirection in c++

I'm trying to understand the strange behavior of the following program. 我试图了解以下程序的奇怪行为。 Obviously, an overflow occurs during the definition of the global variable "bug", but the program throws a floating point exception during the innocent calculation 1.0+2.0. 显然,在定义全局变量“ bug”的过程中会发生溢出,但是在无辜计算1.0 + 2.0期间,程序将引发浮点异常。

#include <iostream>
#include <cmath>
#include <fenv.h>

using namespace std;

const double bug = pow(10.0,pow(10.0,10.0));

int main(void)
{
  feenableexcept(-1);

  cout << "before" << endl;
  cout << 1.0 + 2.0 << endl;
  cout << "after" << endl;

  return 0;
}

I tried compiling it with both g++ and clang++, but got the same output in both 我尝试使用g ++和clang ++对其进行编译,但是两者都得到了相同的输出

before
Floating point exception

const double bug = pow(10.0,pow(10.0,10.0)); should be used. 应该使用。 Because pow need (double,double) argument and you are passing (int,int) 因为pow需要(double,double)参数,并且您正在传递(int,int)

Once I encountered similar case when floating point error manifested itself at strange places. 一旦遇到类似情况,浮点错误就会在奇怪的地方显现出来。 As I understood this happened because FPU status register is syncronized not during every floating point instruction so error may appear to be random. 据我了解,发生这种情况是因为FPU状态寄存器不是在每个浮点指令期间都同步的,所以错误似乎是随机的。 By the way, I've just compiled and started your program and it finished without any issues. 顺便说一句,我刚刚编译并启动了您的程序,它的完成没有任何问题。 My solution was to clear FPU status register after faulty calculation (of course this is hack but at that time I couldn't analize that math library). 我的解决方案是在错误的计算后清除FPU状态寄存器(当然这是hack,但那时我无法分析该数学库)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM