using gdb to debug c program

本文通过一个C语言程序实例,详细介绍了如何使用GCC编译器和GDB调试器进行程序调试,包括设置断点、单步执行及查看变量状态等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
static void display(int i, int *ptr);

int main(void) {
   int x = 5;
   int *xptr = &x;
   printf("In main():\n");
   printf("   x is %d and is stored at %p.\n", x, &x);
   printf("   xptr points to %p which holds %d.\n", xptr, *xptr);
   display(x, xptr);
   return 0;
}

void display(int z, int *zptr) {
   printf("In display():\n");
   printf("   z is %d and is stored at %p.\n", z, &z);
   printf("   zptr points to %p which holds %d.\n", zptr, *zptr);
}



使用上面的file, 比如 test.c

1, 编译。 gcc -g -o testx test.c

2, 运行。 gdb testx

GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 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 "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from testx...done.
(gdb)


3, 设置断点。 gdb> b 8

Breakpoint 1 at 0x8048472: file test.c, line 8.

4, 设置断点2。 gdb> b 10

Breakpoint 2 at 0x80484ac: file test.c, line 10.

5, 执行。 gdb> run

Starting program: /home/wang/mytest/gdbtest/testx 
In main():


Breakpoint 1, main () at test.c:8
8   printf("   x is %d and is stored at %p.\n", x, &x);

6, 继续。 gdb> c

Continuing.
   x is 5 and is stored at 0xbfffeb58.
   xptr points to 0xbfffeb58 which holds 5.


Breakpoint 2, main () at test.c:10
10   display(x, xptr);

7, 继续。 gdb> c

Continuing.
In display():
   z is 5 and is stored at 0xbfffeb40.
   zptr points to 0xbfffeb58 which holds 5.
[Inferior 1 (process 11616) exited normally]




9, for step, using step

10, for backtrace, using bt


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值