Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gdb gives strange output when using math.h functions [duplicate]

Tags:

c

gdb

Possible Duplicate:
Why does gdb evaluate sqrt(3) to 0?

C newbie here. There must be an obvious explanation why gdb gives strange outputs when trying to use math.h functions in-line. For example, the fabs function below is supposed to take the absolute value, and return a double.

(gdb) p cos(2*3.141/4)
$13 = 1073291460
(gdb) p fabs(-3)    
$14 = 0
(gdb) p fabs(3)
$15 = 0
(gdb) p fabs(3.333)
$16 = 1
(gdb) p (double) fabs(-3.234)
$17 = 1
(gdb) p (double) fabs((double)-3.234)
$18 = 1
(gdb) p ((double(*)(double))fabs)(-3)
$19 = 682945

The code I'm using has included math.h, and the actual code appears to execute correctly, although the same code placed in-line in gdb produces strange results. I could ignore it, but it seems a good learning opportunity.

like image 304
ggkmath Avatar asked Dec 20 '11 02:12

ggkmath


People also ask

What are the operators used in the GDB?

GDB supports these operators in addition to those of programming languages: `@'is a binary operator for treating parts of memory as arrays. See section Artificial arrays, for more information. `::'allows you to specify a variable in terms of the file or function where it is defined.

What is output output format in gdb?

Output formats By default, GDB prints a value according to its data type. Sometimes this is not what you want. For example, you might want to print a number in hex, or a pointer in decimal. Or you might want to view data in memory at a certain address as a character string or as an instruction.

What are the functions available in math H library?

C Library math.h functions. The math.h header defines various mathematical functions and one macro. All the functions available in this library take double as an argument and return double as the result. Let us discuss some important functions one by one.

Is it possible to use c++ notation in gdb expressions?

(gdb) p 'f2.c'::x This use of `::'is very rarely in conflict with the very similar use of the same notation in C++. GDB also supports use of the C++ scope resolution operator in GDB expressions.


1 Answers

(Ref: http://lists.gnu.org/archive/html/gdb/2009-12/msg00004.html)

gdb is missing the debug information of the cos function, and therefore assume it is an int cos(...) function, so the values are not returned correctly (esp. on x86 as the registers to store floating point return and integer return are different).

This could be worked around by specifying the type:

(gdb) p ((double(*)(double))cos) (1.0)
$18 = 0.54030230586813977
like image 164
kennytm Avatar answered Nov 15 '22 16:11

kennytm