Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break on NaNs or infs

It is often hard to find the origin of a NaN, since it can happen at any step of a computation and propagate itself. So is it possible to make a C++ program halt when a computation returns NaN or inf? The best in my opinion would be to have a crash with a nice error message:

Foo: NaN encoutered at Foo.c:624

Is something like this possible? Do you have a better solution? How do you debug NaN problems?

EDIT: Precisions: I'm working with GCC under Linux.

like image 233
static_rtti Avatar asked Mar 01 '23 00:03

static_rtti


2 Answers

You can't do it in a completely portable way, but many platforms provide C APIs that allow you to access the floating point status control register(s).

Specifically, you want to unmask the overflow and invalid floating-point exceptions, which will cause the processor to signal an exception when arithmetic in your program produces a NaN or infinity result.

On your linux system this should do the trick:

#include <fenv.h> 
...
feenableexcept(FE_INVALID | FE_OVERFLOW);

You may want to learn to write a trap handler so that you can print a diagnostic message or otherwise continue execution when one of these exceptions is signaled.

like image 170
Stephen Canon Avatar answered Mar 07 '23 01:03

Stephen Canon


Yes! Set (perhaps more or less portably) your IEEE 754-compliant processor to generate an interrupt when a NaN or infinite is encountered.

I googled and found these slides, which are a start. The slide on page 5 summarizes all the information you need.

like image 39
Pascal Cuoq Avatar answered Mar 07 '23 00:03

Pascal Cuoq