views:

179

answers:

1

I have a g++ program that runs without user input. Somewhere the program is interrupted and it says "Floating point exception." Can gdb help me find what's causing this in my code? How?

+4  A: 

You can get help on GDB here and at Gnu's site here.

But the basics are this:

$ gdb ./your_program             // start gdb on the program
> run                            // run the program
> run argv1 argv2                // or run it with command line arguments
(floating point exception)       // let it run until exception occurs
> bt                             // bt will show the stack trace

Here are some gdb settings on how to make sure it stops on floating point exceptions.

Stephen
When I run bt I ge #0 0x0000000000403519 in main (). But I can't figure out what to do with that.
Phenom
Did you build with the -g option to include debugging symbols?
WhirlWind
When I do that, I get Program received signal SIGFPE, Arithmetic exception.0x0000000000403519 in main (argc=1, argv=0x7fffffffe448) at btree.cpp:1310. Then when I run bt I get #0 0x0000000000403519 in main (argc=1, argv=0x7fffffffe448) at btree.cpp:13101310 total = (end-start)/(frequency/1000); So now I can see what line in the program is causing it, but I'm still not sure how to fix it.
Phenom
Likely, frequency is 0 or very close to it, though there may be other reasons. I can't fix it either without seeing your code. What does gdb show when you print frequency?
WhirlWind
Is `frequency` a float? Note that c uses integer division (by default), so if frequency is an integer less than 1000, `frequency/1000` will always be `0`. Divide by zero is usually an FPE.
Stephen
frequency is an int. When I print frequency I get $1 = 0
Phenom
change it to `((frequency+0.000001)/1000.0)` to avoid dividing by zero. Or you may have a prettier approach, hard to tell without the code.
Stephen
I just set frequency = 1000 right after it is declared and that fixed the problem. The function that was supposed to set the value of frequency was commented out so frequency was just 0 before.
Phenom
@Stephen that approach works unless frequency is -0.000001
WhirlWind
@Whirlwind: heh, True, except that he said it's an integer.
Stephen
@Stephen oops, my mistake.
WhirlWind