linux内存越界问题定位,内存越界的一种定位方法

#include

#include

#include

void fn(char *str)

{

memset(str, 0, 64);

return;

}

int main(int argc, char **argv)

{

char badstr[32] = "abc";

int fd = 1;

printf("badstr = %s\n", badstr);

printf("fd = %d\n", fd);

fd = 2;

printf("fd = %d\n", fd);

fn(badstr);

printf("fd = %d\n", fd);

printf("badstr = %s\n", badstr);

return 0;

}

上述代码明显内存越界,一个watch搞定。

以下是定位过程:

[root@localhost qiyk]# ./test

badstr = abc

fd = 1

fd = 2

fd = 0

badstr =

总线错误[程序因内存越界异常退出]

[root@localhost qiyk]# ./gdb test

GNU gdb Red Hat Linux (6.6-8.fc7rh)

Copyright (C) 2006 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License,

welcome to change it and/or distribute copies of it under certain

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB.  Type "show warranty" fo

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

Using host libthread_db library "/lib/i686/nosegneg/libthread_db.

(gdb) b main

Breakpoint 1 at 0x80484cb: file test.cpp, line 13.

(gdb) r

Starting program: /home/qiyk/test

Breakpoint 1, main () at test.cpp:13

13          char badstr[32] = "abc";

(gdb) n

14          int fd = 1;

(gdb) watch fd

Hardware watchpoint 2: fd

(gdb) c

Continuing.

Hardware watchpoint 2: fd[第一次人为修改,此处中断]

Old value = 6317008

New value = 1

main () at test.cpp:15

15          printf("badstr = %s\n", badstr);

(gdb) c

Continuing.

badstr = abc

fd = 1

Hardware watchpoint 2: fd[第二次人为修改,此处中断]

Old value = 1

New value = 2

main () at test.cpp:18

18          printf("fd = %d\n", fd);

(gdb) c

Continuing.

fd = 2

Hardware watchpoint 2: fd[第三次意外修改,此处中断]

Old value = 2

New value = 0

0x004ea367 in memset () from /lib/i686/nosegneg/libc.so.6

(gdb) bt[查看现场堆栈]

#0  0x004ea367 in memset () from /lib/i686/nosegneg/libc.so.6

#1  0x080484b8 in fn (str=0xbf92bd20 "") at test.cpp:7

#2  0x0804854d in main () at test.cpp:19

(gdb) up

#1  0x080484b8 in fn (str=0xbf92bd20 "") at test.cpp:7

7           memset(str, 0, 64);[问题点出现:str越界,导致fd值变为0] (gdb) q The program is running.  Exit anyway? (y or n) y

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值