Trapping floating-point overflow in C

前端 未结 1 1573
温柔的废话
温柔的废话 2021-01-18 11:14

I am trying to trap floating-point overflow in C. Here is what I have tried

#define _GNU_SOURCE

#include 
#include 
#include          


        
1条回答
  •  无人及你
    2021-01-18 11:27

    A floating point exception is translated in machine- and OS-dependent way to some signaling approach. But no such way allows mixing of different constant spaces, as FE_xxx and SIGxxx. Using FE_DIVBYZERO for signal(), you really caught SIGILL which is not generated for floating-point errors (because you did not specify OS, I was free to choose any - Linux in my case).

    For your program, I have made this exception catching working under Linux with two changes:

    1. Setting signal number to handle to SIGFPE.

    2. Declaring a, b, c as volatile (prevents compiler from calculating c as INF at compile time).

    After this, the program fell into eternal cycle printing "caught division by zero" because signal handler for such error restores execution to the same command. You shall carefully consider how to fix such errors without making an erroneous instruction eternal. For example, you can use longjmp to go out of signal handler to an installed exception handler.

    And, you still should consult your target OS manuals for how to catch FP errors.

    (This has been already described in comments in main parts - but I considered to form an explicit answer.)

    0 讨论(0)
提交回复
热议问题