當 gcc C++ 程式崩潰時,如何自動生成堆疊跟蹤?


對於 Linux,我們可以使用 gcc 來編譯 C/C++ 程式碼。此編譯器使用 glibc 庫。我們能夠使用 backtrace() 函式來跟蹤錯誤。這個函式位於 execinfo.h 標頭檔案中。在此示例中,我們將使用堆疊跟蹤功能來顯示分段錯誤。

示例

#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void error_handler(int sig) {
   void *array[10];
   size_t size;
   size = backtrace(array, 10); //get the void pointers for all of the entries
   cout << "Error: signal "<< sig <<":\n"; //display error signal
   backtrace_symbols_fd(array, size, STDERR_FILENO);
   exit(1);
}
void invalid_index() {
   int *ptr = (int*) - 1;
   cout << *ptr << endl; // segmentation error
}
void func1() {
   invalid_index();
}
void func2() {
   func1();
}
int main(int argc, char **argv) {
   signal(SIGSEGV, error_handler); // use handler to print the errors
   func2(); // this will call all other function to generate error
}

輸出

Error: signal 11:
./a.out(+0x825)[0x5579a31d7825]
/lib/x86_64-linux-gnu/libc.so.6(+0x3ef20)[0x7f7689009f20]
./a.out(+0x880)[0x5579a31d7880]
./a.out(+0x8a1)[0x5579a31d78a1]
./a.out(+0x8ad)[0x5579a31d78ad]
./a.out(+0x8d5)[0x5579a31d78d5]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xe7)[0x7f7688fecb97]
./a.out(+0x71a)[0x5579a31d771a]

更新於: 30-7-2019

2K+ 瀏覽次數

開啟您的 職業生涯

透過完成課程取得認證

開始學習
廣告
© . All rights reserved.