程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 內存越界的一種定位方法

內存越界的一種定位方法

編輯:C++入門知識

[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

 

 

 


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved