Division by zero does not throw SIGFPE

纵然是瞬间 提交于 2019-11-27 23:16:58

问题


I have a small program performing floating-point division by zero, so I expect SIGFPE.

#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

void signal_handler (int signo) {
    if(signo == SIGFPE) {
      std::cout << "Caught FPE\n";
    }
}

int main (void) {
  signal(SIGFPE,(*signal_handler));

  double b = 1.0;
  double c = 0.0;
  double d = b/c;
  std::cout << "d = "<< d << std::endl;
  return 0;
}

Actually, I got the following output:

d = inf

gcc version 4.5.2 (Ubuntu/Linaro 4.5.2-8ubuntu4)

What should I do to throw SIGFPE in this case? Which factors FP operation behaviour depend on (compiler flags/CPU type and so on)?

Thanks


回答1:


For floating point numbers you can change this behavior by setting up FPU control word. Take a look here




回答2:


You only get a signal if you perform an integer division by zero. For floating point numbers division by zero is well defined.

This is actually explained rather well in the Wikipedia article.




回答3:


You don't get a signal because the default behavior on most machines is to pollute your data with NaNs (not-a-number) and infinities. You have to enable floating point exceptions, and how you do that is machine specific. Look at the system header fenv.h, if you have one. The function fesettrapenable enables catching floating point exceptions on many machines.

Unfortunately, there is no standard function to turn floating point exceptions handling on.



来源:https://stackoverflow.com/questions/7267838/division-by-zero-does-not-throw-sigfpe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!