當程式產生 segmentation fault 時,系統會將當時的所有狀態,包括變數值,記憶體資料以及程式中各個函式的呼叫狀態 dump 成一個 core file。 我們可以用 GDB 來讀取 core file,分析當時引發 segmentation fault 的原因。
下面的程式嘗試寫入記憶體位址為 0 的區域,引發系統產生 segmentation fault
#include
//This function will cause "Segmentation fault"
void memory_violation()
{
char* ptr = 0;
for(int i=0; i<10 br="" i=""> {
ptr[i] = i;
}
}
int main(int argc, char* argv[])
{
memory_violation();
return 0;
}
編譯指令
$ g++ -g test.cpp -o mytest
設定 core file 最大 size
core file size 預設為 0,這裡改成沒有限制
$ ulimit -c unlimited
執行程式
$ ./mytest
Segmentation fault (core dumped)
利用 GDB 讀取 core file
利用 bt 找出發生錯誤的地方
利用 list *ADDRESS 列出產生錯誤的程式碼
利用 print 觀察變數值
$ gdb ./mytest core
...
(gdb) bt
#0 0x08048405 in memory_violation () at test.cpp:9
#1 0x08048427 in main () at test.cpp:15
(gdb) list *0x08048405
0x8048405 is in memory_violation() (test.cpp:9).
4 void memory_violation()
5 {
6 char* ptr = 0;
7 for(int i=0; i<10 br="" i="">8 {
9 ptr[i] = i;
10 }
11 }
12
13 int main(int argc, char* argv[])
(gdb) print ptr
$1 = 0x0
10>10>
沒有留言:
張貼留言