gdb数据断点监控

开发中经常遇到某个变量明明已经赋值了,但是最后得到的结果却并非赋予的值。解决这样问题让人很头疼,原因我们可能都知道,可能是内存越界导致这部分值被覆盖掉了,但是什么时候被覆盖掉的呢?总不能在每个怀疑的地方打印这个值吧?这样效率很低,而且定位不一定准确。这个时候使用gdb调试中的watch就可以轻松搞定。

顾名思义跟linux中的watch命令类似:实时的监视你需要查看的内容。比如下面程序:

#include <stdio.h>
int main()
{
  int a;
  int b;
  int c;
  a = 1;
  b = 2;
  c = 3;
  memset(&a,0,4*sizeof(int));
  printf("%d %d \n", b, c);
  return 0;
}
执行上面的程序会发现 b和c的值都是0,从代码中看很容易发现是memset越界了,将a以外的内存也清零了,接下来再用watch看看:

首先用gdb加载程序

root@ubuntu:/home/test# gdb ./test
GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04
Copyright (C) 2012 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".
For bug reporting instructions, please see:
<http://bugs.launchpad.net/gdb-linaro/>...
Reading symbols from /home/test/test...done.
(gdb)
接下来watch变量的时候要注意,watch命令执行的时间节点变量必须存在,比如还没进入某个函数你就无法watch这个函数中的局部变量。要是全局变量呢?当然就没有这个限制了,原因显而易见:watch的前提是目标存在的。比如:

(gdb) b main 
Breakpoint 1 at 0x80483ed: file test.c, line 7.
(gdb) watch b
No symbol "b" in current context.//现在还有变量b
(gdb) r
Starting program: /home/test/test 
 
Breakpoint 1, main () at test.c:7
7      a = 1;
(gdb) watch b
Hardware watchpoint 2: b//已经进入main函数,变量b存在 
watch之后,继续执行,变量如果被改变,程序会被停下来:

(gdb) c
Continuing.
Hardware watchpoint 2: b
 
Old value = 134513753//没有初始化b是随机值
New value = 2
main () at test.c:9
9      c = 3;
(gdb) c
Continuing.
Hardware watchpoint 2: b
 
Old value = 2
New value = 0
0x08048416 in main () at test.c:10
10      memset(&a,0,4*sizeof(int));//这里越界导致b,c被修改
(gdb) c
Continuing.
0 0 
是不是很方便。编译时记得加上-g选项方便调试
--------------------- 
作者:L.G.F 
来源:CSDN 
原文:https://blog.csdn.net/u010659887/article/details/89677351 
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值