delhi_loafer delhi_loafer - 1 year ago 76
C++ Question

GDB prints arbitrary values when round() function called during debugging a C++ program

I am debugging a c++ (mex) program using gdb. In the code threre is a statement where a variable is assigned a rounded value of another variable. For instance:

x = round(y);

The assignment works correctly and when I call at the gdb prompt
(gdb) print x
, the correct value is printed. However, when I call
(gdb) print round(y)
, a strange arbitrary number is printed.

Any idea what could be a source of this strange behaviour?

Answer Source

I was able to reproduce this oddity on Ubuntu. gdb is having trouble with the double input and double return value.

There appears to be an easy workaround however by calling __round.

(gdb) p round
$6 = {<text variable, no debug info>} 0x7ffff77f7460 <__round>
(gdb) p round(1.3)
$7 = -858993460
(gdb) p __round(1.3)
$8 = 1
(gdb) p __round
$9 = {double (double)} 0x7ffff77f7460 

Note that gdb prototype for __round appears correct while the parameter type information is missing for round. As a result, it is appears that the input/output are considered as ints to round.

The man page for round says that if x is integral then it will be directly returned. If we assume that gdb is converting the double to an int then it explains the output.

11    double y = 1.3;
(gdb) n
13    int k = round(y);
(gdb) p /x round(y)
$28 = 0xcccccccd
(gdb) p /lx *(long*)&y
$29 = 0x3ff4cccccccccccd

So gdb is truncating the input value to 32-bit int and sending an int to round which sends it right back. Thus the lower word of the double is the output. Or perhaps it is truncating the return value to 32-bit with the same result.

As to why gdb doesn't have a proper prototype for round, I'm not sure.

Good question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download