您的位置:首页 > 编程语言 > C语言/C++

从gdb角度分析,为什么C语言中的scanf函数的变量要用“&”表示首地址

2009-09-02 21:50 316 查看
gdb.c程序代码如下:

include<stdio.h>

int main(void)

{

  int input=0;

  printf("Enter an integer:");

  scanf("%d",input);

  printf("Twice the number you supplied is %d./n",2*input);

  return 0;

}

用gdb默认方式编译

[quan@fedora c]$ gcc -Wall -o gdb gdb.c

gdb.c: In function ‘main’:

gdb.c:6: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

[quan@fedora c]$ ./gdb

Enter an integer:5

Segmentation fault

 用ggdb3编译

[quan@fedora c]$ gcc -ggdb3 -Wall -o gdb gdb.c

gdb.c: In function ‘main’:

gdb.c:6: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘int’

[quan@fedora c]$ ./gdb

Enter an integer:5

Segmentation fault

然后允许使用存储信息

[quan@fedora c]$ ulimit -c unlimited

[quan@fedora c]$ ./gdb

Enter an integer:5

Segmentation fault (core dumped)

调试加入core

[quan@fedora c]$ gdb gdb core

GNU gdb (GDB) Fedora (6.8.50.20090302-38.fc11)

Copyright (C) 2009 Free Software Foundation, Inc.

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software: you are free to change and redistribute it.

There is NO WARRANTY, to the extent permitted by law.  Type "show copying"

and "show warranty" for details.

This GDB was configured as "i586-redhat-linux-gnu".

For bug reporting instructions, please see:

<http://www.gnu.org/software/gdb/bugs/>...

/home/quan/test/c/core: No such file or directory.

(gdb) r

Starting program: /home/quan/test/c/gdb

Enter an integer:5

Program received signal SIGSEGV, Segmentation fault.

0x005837b6 in _IO_vfscanf_internal () from /lib/libc.so.6

Missing separate debuginfos, use: debuginfo-install glibc-2.10.1-4.i686

(gdb) bt

#0  0x005837b6 in _IO_vfscanf_internal () from /lib/libc.so.6

#1  0x00590239 in __isoc99_scanf () from /lib/libc.so.6

#2  0x08048447 in main () at gdb.c:6

(gdb) frame 2

#2  0x08048447 in main () at gdb.c:6

6      scanf("%d",input);

(gdb) print input

$1 = 0

(gdb) q

The program is running.  Quit anyway (and kill it)? (y or n) y

原来input前没加&。

修改程序为:

include<stdio.h>

int main(void)

{

  int input=0;

  printf("Enter an integer:");

  scanf("%d",&input);

  printf("Twice the number you supplied is %d./n",2*input);

  return 0;

}

然后编译运行

[quan@fedora c]$ gcc -ggdb3 -Wall -o gdb gdb.c

[quan@fedora c]$ ./gdb

Enter an integer:5

Twice the number you supplied is 10.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息