Is it possible to break the execution in gdb at the first assignment of inf?

Viewed 577

Is there a command in gdb that I can run to make it automatically stop (break) at the first occurrence of assignment of NaN or inf to a variable, that is when RHS of an executed assignment is NaN or inf (for example when I divide something by zero and try to assign the result to a variable)?

2 Answers

With gcc on Linux you can turn floating-point exceptions to SIGFPE signal. You can call feenableexcept(FE_DIVBYZERO) to catch all subsequent floating point divisions by zero in your code. If you run this code in gdb it will stop on SIGFPE signal. This is default behavior for most other signals as well. This code was taken and modified from here: https://stackoverflow.com/a/2949452/72178

#define _GNU_SOURCE
#include <fenv.h>

int main(void) {
    double x, y, z;
    feenableexcept(FE_DIVBYZERO);

    x = 1;
    y = 0;
    z = x / y;

    return 0;
}

gdb will stop on division by zero:

$ gdb -q ./a.out
Reading symbols from ./a.out...
(gdb) r
Program received signal SIGFPE, Arithmetic exception.
0x0000000000401153 in main () at 1.c:10
10      z = x / y;
(gdb) 

Under many aspects, NaN is a value like any other. Therefore, I don't believe that it is possible to have this generate a special event in every case.

Depending on the architecture you are programming for, there may be a division-by-zero event which might be quite easy to catch. Note however that divisions by zero are not the only way to produce a NaN value. (Again depending on the architecture) performing another operation with a NaN operant may raise an event/exception (e. g., "invalid operation"). This may point into some direction to generate a gdb breakpoint by adding some code to the system under debug (if that is an option).

Beside triggers from exception events, conditional watchpoints may be an option: If you aren't just looking for NaN values anywhere, a watchpoint on a certain variable, which is limited to a condition can be a good solution.

Under certain circumstances, both ideas won't help you further: If, for example, the NaN appears at some places in a buggy (or unstable) numeric implementation in HPC context, additional numeric operations and conditional breakpoints/watchpoints normally aren't feasible because the overhead will "choke" the calculation before it even generated NaN values.

Related