内存越界的一种定位方法
[cpp]
#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;
}
#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
补充:软件开发 , C++ ,