在不具備gdb環境的類Linux系統開發板上調試段錯誤,大致定位出錯函數位置
理論知識就不講了,想瞭解的可以在搜尋下“Linux下的段錯誤產生的原因及調試方法” 這篇文章,本文的內容基本是從那文章裡提取出來的。
1 初步步驟:
1)在你的代碼中添加如下代碼:
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void dump(int signo)
{
void *array[30];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 30);
strings = backtrace_symbols (array, size);
fprintf (stderr,"Obtained %zd stack frames.nm", size);
for (i = 0; i < size; i++)
fprintf (stderr,"%sn", strings[i]);
free (strings);
exit(0);
}
Debug_Printf_FrameInfos()
{
signal(SIGSEGV, &dump);
}
2)
在你的mian函數中調用 Debug_Printf_FrameInfos(); 函數。
最好在mian函數的開頭。
3)編譯器時 加 -g 選項
2:如何定位出錯函數地址
這裡以 test.c 為例,來尋找出錯函數地址
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
void dump(int signo)
{
void *array[30];
size_t size;
char **strings;
size_t i;
size = backtrace (array, 30);
strings = backtrace_symbols (array, size);
fprintf (stderr,"Obtained %zd stack frames.nm", size);
for (i = 0; i <= size; i++)
fprintf (stderr,"%s/n", strings[i]);
free (strings);
exit(0);
}
Debug_Printf_FrameInfos()
{
signal(SIGSEGV, dump);
}
void c()
{
* ((volatile char *) 0x0) = 0x999;
}
void b()
{
c();
}
void a()
{
b();
}
int main()
{
Debug_Printf_FrameInfos();
a();
return 0;
}
該常式功能是
main()->a()->b()->c()->出錯。
a)編譯器: gcc -g test.c -o test
b)運行 test程式: ./test
c)程式將列印如下資訊:
Obtained 7 stack frames.nm./a.out [0x80484f3]
[0xffffe420]
./a.out [0x80485ad]
./a.out [0x80485b7]
./a.out [0x80485d4]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xdc) [0xb7dc4ebc]
./a.out [0x8048451]
d) objdump -d text > tmp
e)在tmp 中尋找0x80485ad的地址,你會發現如下資訊:
080485a5 <b>:
80485a5: 55 push %ebp
80485a6: 89 e5 mov %esp,%ebp
80485a8: e8 eb ff ff ff call 8048598 <c>
80485ad: 5d pop %ebp
80485ae: c3 ret
其中:
80485ad: 5d pop %ebp
是調用( call 8048598 <c>)c函數後的地址, 雖然沒有直接定位到C函數,但已經定位到B了,這在大型的程式中確是非常有用的。
(本常式的結果可能會隨著C庫的不同而不同)