gpt4 book ai didi

c - 为什么 gdb 将 sqrt(3) 评估为 0?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:07 25 4
gpt4 key购买 nike

3 的平方根,由 Wolfram Alpha 估计:

1.7320508075688772935274463415058723669428052538103806280558...

当我在 C 中执行 sqrt(3) 时,它的计算结果为 0。为什么?

EDIT4:以下是如何在 GDB 中重现此问题。如下创建test.c:

#include <stdio.h>                                                                                                                                                                      
#include <math.h>

int main()
{
printf("sqrt(3): %f\n", sqrt(3));
return 0;
}

编译:

gcc -O0 -g -Wall -pedantic -ansi -lm -o test test.c

运行调试器:

gdb test

在控制台输入:

(gdb) break test.c:6
Breakpoint 1 at 0x400578: file test.c, line 6.
(gdb) r
Starting program: /home/pdedecker/Desktop/test
Breakpoint 1, main () at test.c:6
6 printf("sqrt(3): %f\n", sqrt(3));
(gdb) print sqrt(3)
$1 = 0
(gdb) s
sqrt(3): 1.732051

我的 GDB 版本是 GNU gdb (GDB) SUSE (7.1-3.12)

最佳答案

问题不在于缺少函数声明(它并没有丢失,因为您确实包含了 <math.h> )。

问题是缺少 sqrt 的调试信息你实际上正在使用。没有调试信息,GDB 不知道要传递给 sqrt() 的参数类型。 ,以及它返回的内容。

您可以通过安装 libc-debuginfo 软件包在许多 Linux 发行版上获得所需的调试信息。这是我在这样的系统上看到的:

gdb -q ./a.out
Reading symbols from /tmp/a.out...done.
(gdb) b main
Breakpoint 1 at 0x400558: file t.c, line 6.
(gdb) r

Breakpoint 1, main () at t.c:6
6 printf("sqrt(3): %f\n", sqrt(3));
(gdb) p sqrt
$1 = {<text variable, no debug info>} 0x7ffff7b7fb50 <__sqrt>

注意:“没有调试信息”

(gdb) p sqrt(3)
$2 = 0
(gdb) p sqrt(3.0)
$3 = 0

注意:匹配你的行为。什么sqrt函数调试信息吗?

(gdb) info func sqrt
All functions matching regular expression "sqrt":

File ../sysdeps/x86_64/fpu/e_sqrt.c:
double __ieee754_sqrt(double);

File s_csqrt.c:
complex double __csqrt(complex double);

File ../sysdeps/x86_64/fpu/e_sqrtf.c:
float __ieee754_sqrtf(float);

File w_sqrtf.c:
float __sqrtf(float);

File s_csqrtf.c:
complex float __csqrtf(complex float);

File ../sysdeps/i386/fpu/e_sqrtl.c:
long double __ieee754_sqrtl(long double);

File w_sqrtl.c:
long double __sqrtl(long double);

File s_csqrtl.c:
complex long double __csqrtl(complex long double);

File ../sysdeps/ieee754/dbl-64/mpsqrt.c:
void __mpsqrt(mp_no *, mp_no *, int);

File w_sqrt.c:
double __sqrt(double);

(gdb) p __sqrt
$4 = {double (double)} 0x7ffff7b7fb50 <__sqrt>

备注:__sqrtsqrt 位于同一地址, 但 GDB 知道它的类型!

(gdb) p __sqrt(3)
$5 = 1.7320508075688772
(gdb) p __sqrt(3.0)
$6 = 1.7320508075688772

可以合理地说这是 GDB 中的错误。欢迎在 GDB bugzilla 中创建一个.

关于c - 为什么 gdb 将 sqrt(3) 评估为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47947435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com