打印函数调用堆栈
有時候調試bug需要知道某個函數從哪里調用導致出了問題的,就需要打印函數調用堆棧信息,在Linux可以使用backtrace函數來實現,下面是一個簡單的例子:
1 #include <cstdio> 2 #include <cstdlib> 3 #include <execinfo.h> 4 5 using namespace std; 6 7 void Test3(int i) 8 { 9 printf("Hello world!\n"); 10 11 int nptrs; 12 void *buffer[100]; 13 char **strings; 14 15 nptrs = backtrace(buffer, 10); 16 printf("backtrace returned %d address\n", nptrs); 17 strings = backtrace_symbols(buffer, nptrs); 18 for (int j = 0; j < nptrs; ++j) 19 { 20 printf("%s\n", strings[j]); 21 } 22 23 free(strings); 24 } 25 26 void Test2(int i) 27 { 28 Test3(i); 29 } 30 31 void Test1(int i) 32 { 33 Test2(i); 34 } 35 36 int main(int argc, char **argv) 37 { 38 Test1(1); 39 40 return 0; 41 }編譯:
?g++ -rdynamic -o testDumpStack ./testDumpStack.cpp?
執行結果:
轉載于:https://www.cnblogs.com/lit10050528/p/6056283.html
總結
- 上一篇: Netty方法误解ChannelHand
- 下一篇: Codeforces Round #36