C program generates incorrect fp exception under gcc.
Aaron Sosnick
aaron@caxton.com
Thu Oct 21 12:07:00 GMT 1999
Consider the following C program foo.c compiled with gcc-2.95.1
on a Solaris Sparc platform. (I imagine the results are the same
for all IEEE floating point machines. The issue exists back until
at least gcc-2.7.2 and probably much earlier)
> #include <math.h>
> #include <values.h>
>
> main() {
>
> int a;
> float b;
>
> if (0!=ieee_handler("set","common",SIGFPE_ABORT)) {
> perror("Unable to set ieee_abort");
> abort();
> }
>
> b=MAXINT;
> b+=1.0; /* get a fp value too big for an int */
>
> a=b; /* implicit cast from float to int. Program aborts. */
> printf("%d\n",a);
> }
> $ gcc-2.95.1 foo.c -lm
> $ ./a.out
> Abort (core dumped)
The program aborts at the second commented line. A floating point
"invalid" exception is generated there. If the exception wasn't set to
abort, a would be set to MAXINT.
I can see somebody making the argument that this isn't a bug.
ANSI C says that the results of a cast from a too large floating point
value to an integer value is undefined, therefore no compiler
behavior can be wrong, it's the C program which is wrong.
On the other hand, shouldn't gcc do something reasonable? A return
value of MAXINT seems reasonable. Rasing an fp exception
doesn't. First, it seems that this is an integer overflow, not an fp
one. Second, the IEEE standard says that all untrapped "invalid"
exceptions result in NaN which isn't (can't be) the case here.
I'd appreciate it if somebody knowledgable had time to comment.
A little background on this behavior would help, even if it
doesn't get treated as a bug. I haven't been able to find any
documention or previous newsgroup discussions of this issue.
It may seem a bit academic but it turns out that there
is important code out there (Perl) that will routinely
cast floats greater MAXINT into ints.
Thanks
More information about the Gcc-bugs
mailing list