您的位置:首页 > 其它

修改中断内存越界的一种定位方法

2013-05-17 22:08 330 查看
时间紧张,先记一笔,后续优化与完善。

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

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

文章结束给大家分享下程序员的一些笑话语录:

IBM和波音777

  波音777是有史以来第一架完全在电脑虚拟现实中设计制造的飞机,所用的设备完全由IBM公司所提供。试飞前,波音公司的总裁非常热情的邀请IBM的技术主管去参加试飞,可那位主管却说道:“啊,非常荣幸,可惜那天是我妻子的生日,So..”..

  波音公司的总载一听就生气了:“胆小鬼,我还没告诉你试飞的日期呢!”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: