Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does C/C++ handler SIGFPE?

well, I have searched the articles about SIGFPE ,then I wrote a few tests but it's behavoir is strange. Then I have to post it here to ask for help. Is the GCC/G++ or ISO C++ clearly defined what happens if divide by zero?

1) I searched the article : Division by zero does not throw SIGFPE it sames the output is inf

2) If I rewrite it as the following:

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

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

  int b = 1;
  int c = 0;
  int d = b/c;
  //fprintf(stderr,"d number is %d\n,d);
  return 0;
}

then signal_handler will not happens. but if I uncomment the line

//fprintf(stderr,"d number is %d\n,d);

then signal_handler keeps calling.

can someone explains it ?

like image 534
python Avatar asked Feb 16 '13 01:02

python


People also ask

What is SIGFPE in C?

Macro: int SIGFPE. The SIGFPE signal reports a fatal arithmetic error. Although the name is derived from “floating-point exception”, this signal actually covers all arithmetic errors, including division by zero and overflow.

What is Sig_err?

#define SIG_ERR /* implementation defined */ A value of type void (*)(int) . When returned by signal, indicates that an error has occurred.

Which of the following signal is used to generate some erroneous arithmetic operation like divide by zero?

6) Which of the following signal is used to generate some erroneous arithmetic operation like divide by zero? 7) Which of the following signal is used to generate for segmentation violation? Explanation: The SIGSEGV signal is used to generate for segmentation violation.


1 Answers

This is interesting: With the fprintf commented out, the compiler has determined that the calculated result: d = b/c is an unused local expression and can be optimized away.

Clearly though, it is not side-effect free in its execution, but the compiler can't determine anything about the runtime environment at this stage. I'm surprised that static analysis doesn't pick this up as a warning (at least) in a modern compiler.

@vonbrand is right. You got lucky with what you're doing in the (asynchronous) signal handler.


Edit: when you say "signal_handler keeps calling", do you mean it's repeating indefinitely? If so, there could be issues with underlying system calls restarting. Try: siginterrupt(SIGFPE, 1); (assuming it's available).

like image 149
Brett Hale Avatar answered Oct 04 '22 19:10

Brett Hale