10

Is there a simple way to check a C++ code in a debugger for the very first appearance of a NaN value?

Thomas W.
  • 2,134
  • 2
  • 24
  • 46
  • First appearance in what respect? Within an array, vector, algorithm or something else? – Herr von Wurst Aug 13 '12 at 12:03
  • 1
    To make my question clear: In my large and complicated code, a matrix is generated that contains some NaNs. My problem is to trace back where the very first NaN was created. – Thomas W. Aug 13 '12 at 13:03
  • Can you specify how you fill the matrix? If it gets filled dynamically, then you could change data type of matrix member representing single number to be some class. Then you overload its `operator = (float f)`. And inside overload you put assert for NaN. Would that work? – Roman Saveljev Aug 13 '12 at 13:06
  • 5
    okay: there is already a discussion to it: http://stackoverflow.com/q/5393997/1326595 – Thomas W. Aug 13 '12 at 13:11

3 Answers3

12

The answer is given here: https://stackoverflow.com/a/5394095/1326595

Just include

#include <fenv.h>

and than add the following line to the code:

feenableexcept(FE_INVALID | FE_OVERFLOW);

The debugger is than able to capture the signal and shows the very first occurrence of a NaN.

Community
  • 1
  • 1
Thomas W.
  • 2,134
  • 2
  • 24
  • 46
  • 1
    Depending on your environment, you might need to add `#define _GNU_SOURCE ` above the include – Lennart Feb 15 '21 at 17:11
5

By IEEE standard the following condition is false for NaN's:

val == val

and you could use it to trigger assert or software breakpoint, but beware of compiler optimizations. Probably, in debug build it would not get optimized away

Roman Saveljev
  • 2,544
  • 1
  • 21
  • 20
  • 1
    If the standard says val == val should be false for NaN's, then it should _not_ be optimized. An optimization here would be a bug in the compiler. – Daniel Daranas Aug 13 '12 at 12:45
  • @DanielDaranas Yes-yes, you must have read the same thread. There were multitudes of opinions. Someone suggested to declare `val` volatile to feel extra safe. I just could not find it.. – Roman Saveljev Aug 13 '12 at 12:50
  • I know how to check whether a value is NaN or not. But my question is, how to check where the very first NaN was created. The problem is that my final matrix has some NaNs, and now I have to trace back through a very large code where it comes from. – Thomas W. Aug 13 '12 at 12:58
2

You can put an assert(val >= 0 || val <= 0) to catch a NaN

Andrew
  • 24,218
  • 13
  • 61
  • 90