Stopping the debugger when a NaN floating point number is produced
An answer to this question on Stack Overflow.
Question
I have an C++ program. Somewhere in the program (hard to reproduce, but reproduceable) a caclculation results in a float beeing set to a NaN. Since a floating point operation involving a NaN results in a NaN, this spreads fast.
Is there any way I can setup the compiler (gcc 4.4) or the debuger (gdb) to stop when a floating point operation results in a NaN? That would be extremely useful.
Thanks! Nathan
PS: It might matter: I am working under ubuntu linux 10.10.
Answer
You can use feenableexcept like so:
#include <cfenv>
#include <iostream>
int main(){
// Values at: https://cplusplus.com/reference/cfenv/FE_OVERFLOW/
feenableexcept(FE_INVALID);
for(int i=0;i<10;i++){
std::cout<<(i/0.)<<std::endl;
}
return 0;
}