Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

debugging - How to trace a NaN in C++

I am going to do some math calculations using C++ . The input floating point number is a valid number, but after the calculations, the resulting value is NaN. I would like to trace the point where NaN value appears (possibly using GDB), instead of inserting a lot of isNan() into the code. But I found that even code like this will not trigger an exception when a NaN value appears.

double dirty = 0.0;
double nanvalue = 0.0/dirty;

Could anyone suggest a method for tracing the NaN or turning a NaN into an exception?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you mention using gdb, here's a solution that works with gcc -- you want the functions defined in fenv.h :

#define _GNU_SOURCE
#include <fenv.h>
#include <stdio.h>

int main(int argc, char **argv)
{
   double dirty = 0.0;

   feenableexcept(FE_ALL_EXCEPT & ~FE_INEXACT);  // Enable all floating point exceptions but FE_INEXACT
   double nanval=0.0/dirty;
   printf("Succeeded! dirty=%lf, nanval=%lf
",dirty,nanval);
}

Running the above program produces the output "Floating point exception". Without the call to feenableexcept, the "Succeeded!" message is printed.

If you were to write a signal handler for SIGFPE, that might be a good place to set a breakpoint and get the traceback you want. (Disclaimer: haven't tried it!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...