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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值