一次gdb实战 设置断点 单步调试 打印和修改变量值等操作

本案例总结了gdb的常用用法,详细规则可参考gdb入门教程

总结在前:

  1. 编译命令gcc -g gdb_test.c -o gdb_test,通过-g选项添加调试信息,否则使用gdb调试时,会报“No symbol table is loaded. Use the "file" command.”错误。
  2. 设置断点:bread(或b) 函数名; bread(或b) -line 行号;例如b mainb -line 21
  3. 开始运行:run,该命令会直接运行到断点位置或直至结束。
  4. 单步执行:next(n),该命令将程序执行一行。
  5. 打印变量:print 变量名,例如print ret
  6. 修改变量:set 变量名=变量值,例如set ret=1
  7. 多步执行:continue©,继续运行您的程序 (在停止之后,比如在一个断点之后)。

源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct GDB_TEST
{
    /* data */
    int gdb_int;
    char gdb_char[64];
};

static struct GDB_TEST my_dgb_test = 
{
    .gdb_int = 5,
    .gdb_char = "This is my test",
};


void main()
{
    printf("main start\n");
    int ret = -1;
    struct GDB_TEST *test = &my_dgb_test;

    if (test->gdb_int == 0) /* 期望在gdb中,在此修改test->gdb_int的值,使其进入到此分支*/
    {
        ret = 0;
        printf("now ret and gdb_int is 0\n");
    }

    if (test->gdb_int == 1)  /* 期望在gdb中,在此修改test->gdb_int的值,使其进入到此分支*/
    {
        ret = 1;
        printf("now ret and gdb_int is 1\n");
    }
    
    printf("return\n");
	return;
} 

实践:

/* step1: 使用-g选项编译二进制可执行程序 */
[10283203@zte.intra@127 c_code]$ gcc -g gdb_test.c -o gdb_test

/* step2: gdb 文件名 开始gdb调试 */
[10283203@zte.intra@127 c_code]$ gdb gdb_test
GNU gdb (GDB) Red Hat Enterprise Linux 8.2-6.el8
……省略gdb版本信息……
Reading symbols from gdb_test...done.

/* step3:设置断点 */
(gdb) b main 
Breakpoint 1 at 0x40058e: file gdb_test.c, line 21.

/* step4:开始运行*/
(gdb) run
Starting program: /media/vdb1/code_test/c_code/gdb_test 
Missing separate debuginfos, use: yum debuginfo-install glibc-2.28-72.el8_1.1.x86_64

Breakpoint 1, main () at gdb_test.c:21
21          printf("main start\n");

/* 单步执行 */
(gdb) n
main start
22          int ret = -1;
(gdb) n
23          struct GDB_TEST *test = &my_dgb_test;
(gdb) 
25          if (test->gdb_int == 0)

/* step5:print命令查看变量值 */
(gdb) print test->gdb_int
$1 = 5

/* step6:set命令修改变量值,单步执行,通过打印确定修改成功 */
(gdb) set test->gdb_int=0
(gdb) print test->gdb_int
$2 = 0
(gdb) n
27              ret = 0;
(gdb) n
28              printf("now ret and gdb_int is 0\n");
(gdb) n
now ret and gdb_int is 0

/* step6:set命令修改变量值,单步执行,通过打印确定修改成功 */
31          if (test->gdb_int == 1)
(gdb) print test->gdb_int
$3 = 0
(gdb) set test->gdb_int=1
(gdb) print test->gdb_int
$4 = 1
(gdb) n
33              ret = 1;
(gdb) 
34              printf("now ret and gdb_int is 1\n");

/* 执行到程序结束 */
(gdb) c
Continuing.
now ret and gdb_int is 1
return
[Inferior 1 (process 1297) exited with code 07]
(gdb) quit
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值