1. 程式人生 > >Linux下的段錯誤(Segmentation fault)產生的原因及除錯方法

Linux下的段錯誤(Segmentation fault)產生的原因及除錯方法

 段錯誤

就是訪問了錯誤的記憶體段,一般是你沒有許可權,或者根本就不存在對應的實體記憶體,尤其常見的是訪問0地址.

        一 般來說,段錯誤就是指訪問的記憶體超出了系統所給這個程式的記憶體空間,通常這個值是由gdtr來儲存的
是一個48位的暫存器

             前32位是儲存由它指 向的gdt表

             後13位儲存相應於gdt下標

             最後3位包括了程式是否在記憶體中以及程式的在cpu中的執行級別.    指向的gdt是由以64位為一個單位的 表,在這張表中就儲存著程式執行的程式碼段以及資料段的起始地址以及與此相應的段限和頁面交換

還有程式執行級別還有記憶體粒度等等的資訊。一旦一個程式發生了 越界訪問,cpu就會產生相應的異常保護,於是segmentation fault就出現了.


在程式設計中以下幾類做法容易導致段錯誤,基本是錯誤地使用指標引起的

1)訪問系統資料區,尤其是往 系統保護的記憶體地址寫資料,最常見就是給一個指標0地址
2)記憶體越界(陣列越界,變數型別不一致等) 訪問到不屬於你的記憶體區域

解決方法


我 們在用C/C++語言寫程式的時侯,記憶體管理的絕大部分工作都是需要我們來做的。實際上,記憶體管理是一個比較繁瑣的工作,無論你多高明,經驗多豐富,難 免會在此處犯些小錯誤,而通常這些錯誤又是那麼的淺顯而易於消除。但是手工“除蟲”(debug),往往是效率低下且讓人厭煩的,本文將就"段錯誤"這個 記憶體訪問越界的錯誤談談如何快速定位這些"段錯誤"的語句。
下面將就以下的一個存在段錯誤的程式介紹幾種除錯方法:
     1 dummy_function (void)
     2 {
     3          unsigned char *ptr = 0x00;
     4          *ptr = 0x00;
     5 }
     6
     7 int main (void)
     8 {
     9          dummy_function ();
    10
    11          return 0;
    12 }

作為一個熟練的C/C++程式設計師,以上程式碼的bug應該是很清楚的,因為它嘗試操作地址為0的記憶體區域,而這個記憶體區域通常是不可訪問的禁區,當然就會出錯了。我們嘗試編譯執行它:
[email protected] test $ ./a.out
段錯誤

果然不出所料,它出錯並退出了。
1.利用gdb逐步查詢段錯誤:
這種方法也是被大眾所熟知並廣泛採用的方法,首先我們需要一個帶有除錯資訊的可執行程式,所以我們加上“-g -rdynamic"的引數進行編譯,然後用gdb除錯執行這個新編譯的程式,具體步驟如下:
[email protected] test $ gcc -g -rdynamic d.c


[email protected] test $ gdb ./a.out
GNU gdb 6.5
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".

(gdb) r
Starting program: /home/xiaosuo/test/a.out

Program received signal SIGSEGV, Segmentation fault.
0x08048524 in dummy_function () at d.c:4
4               *ptr = 0x00;
(gdb)                     

哦?!好像不用一步步除錯我們就找到了出錯位置d.c檔案的第4行,其實就是如此的簡單。
從這裡我們還發現程序是由於收到了SIGSEGV訊號而結束的。通過進一步的查閱文件(man 7 signal),我們知道SIGSEGV預設handler的動作是列印”段錯誤"的出錯資訊,併產生Core檔案,由此我們又產生了方法二。
2.分析Core檔案:
Core檔案是什麼呢?
The default action of certain signals is to cause a process to terminate and produce a core dump file, a disk file containing an image of the process's memory at the time of termination. A list of the signals which cause a process to dump core can be found in signal(7).

以 上資料摘自man page(man 5 core)。不過奇怪了,我的系統上並沒有找到core檔案。後來,憶起為了漸少系統上的拉圾檔案的數量(本人有些潔癖,這也是我喜歡Gentoo的原因 之一),禁止了core檔案的生成,查看了以下果真如此,將系統的core檔案的大小限制在512K大小,再試:
[email protected] test $ ulimit -c
0
[email protected] test $ ulimit -c 1000
[email protected] test $ ulimit -c
1000
[email protected] test $ ./a.out
段錯誤 (core dumped)
[email protected] test $ ls
a.out core d.c f.c g.c pango.c test_iconv.c test_regex.c

core檔案終於產生了,用gdb除錯一下看看吧:
[email protected] test $ gdb ./a.out core
GNU gdb 6.5
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".


warning: Can't read pathname for load map: 輸入/輸出錯誤.
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
Core was generated by `./a.out'.
Program terminated with signal 11, Segmentation fault.
#0 0x08048524 in dummy_function () at d.c:4
4               *ptr = 0x00;

哇,好歷害,還是一步就定位到了錯誤所在地,佩服一下Linux/Unix系統的此類設計。
接著考慮下去,以前用windows系統下的ie的時侯,有時開啟某些網頁,會出現“執行時錯誤”,這個時侯如果恰好你的機器上又裝有windows的編譯器的話,他會彈出來一個對話方塊,問你是否進行除錯,如果你選擇是,編譯器將被開啟,並進入除錯狀態,開始除錯。
Linux下如何做到這些呢?我的大腦飛速地旋轉著,有了,讓它在SIGSEGV的handler中呼叫gdb,於是第三個方法又誕生了:
3.段錯誤時啟動除錯:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>

void dump(int signo)
{
        char buf[1024];
        char cmd[1024];
        FILE *fh;

        snprintf(buf, sizeof(buf), "/proc/%d/cmdline", getpid());
        if(!(fh = fopen(buf, "r")))
                exit(0);
        if(!fgets(buf, sizeof(buf), fh))
                exit(0);
        fclose(fh);
        if(buf[strlen(buf) - 1] == '\n')
                buf[strlen(buf) - 1] = '\0';
        snprintf(cmd, sizeof(cmd), "gdb %s %d", buf, getpid());
        system(cmd);

        exit(0);
}

        void
dummy_function (void)
{
        unsigned char *ptr = 0x00;
        *ptr = 0x00;
}

        int
main (void)
{
        signal(SIGSEGV, &dump);
        dummy_function ();

        return 0;
}

編譯執行效果如下:
[email protected] test $ gcc -g -rdynamic f.c
[email protected] test $ ./a.out
GNU gdb 6.5
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i686-pc-linux-gnu"...Using host libthread_db library "/lib/libthread_db.so.1".

Attaching to program: /home/xiaosuo/test/a.out, process 9563
Reading symbols from /lib/libc.so.6...done.
Loaded symbols for /lib/libc.so.6
Reading symbols from /lib/ld-linux.so.2...done.
Loaded symbols for /lib/ld-linux.so.2
0xffffe410 in __kernel_vsyscall ()
(gdb) bt
#0 0xffffe410 in __kernel_vsyscall ()
#1 0xb7ee4b53 in waitpid () from /lib/libc.so.6
#2 0xb7e925c9 in strtold_l () from /lib/libc.so.6
#3 0x08048830 in dump (signo=11) at f.c:22
#4 <signal handler called>
#5 0x0804884c in dummy_function () at f.c:31
#6 0x08048886 in main () at f.c:38

怎麼樣?是不是依舊很酷?
以上方法都是在系統上有gdb的前提下進行的,如果沒有呢?其實glibc為我們提供了此類能夠dump棧內容的函式簇,詳見/usr/include/execinfo.h(這些函式都沒有提供man page,難怪我們找不到),另外你也可以通過進行學習。
4.利用backtrace和objdump進行分析:
重寫的程式碼如下:
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

/* A dummy function to make the backtrace more interesting. */
        void
dummy_function (void)
{
        unsigned char *ptr = 0x00;
        *ptr = 0x00;
}

void dump(int signo)
{
        void *array[10];
        size_t size;
        char **strings;
        size_t i;

        size = backtrace (array, 10);
        strings = backtrace_symbols (array, size);

        printf ("Obtained %zd stack frames.\n", size);

        for (i = 0; i < size; i++)
                printf ("%s\n", strings[i]);

        free (strings);

        exit(0);
}

        int
main (void)
{
        signal(SIGSEGV, &dump);
        dummy_function ();

        return 0;
}

編譯執行結果如下:
[email protected] test $ gcc -g -rdynamic g.c
[email protected] test $ ./a.out
Obtained 5 stack frames.
./a.out(dump+0x19) [0x80486c2]
[0xffffe420]
./a.out(main+0x35) [0x804876f]
/lib/libc.so.6(__libc_start_main+0xe6) [0xb7e02866]
./a.out [0x8048601]

這次你可能有些失望,似乎沒能給出足夠的資訊來標示錯誤,不急,先看看能分析出來什麼吧,用objdump反彙編程式,找到地址0x804876f對應的程式碼位置:
[email protected] test $ objdump -d a.out


8048765:       e8 02 fe ff ff          call   804856c <[email protected]>
804876a:       e8 25 ff ff ff          call   8048694 <dummy_function>
804876f:       b8 00 00 00 00          mov    $0x0,%eax
8048774:       c9                      leave