zl程序教程

您现在的位置是:首页 >  其它

当前栏目

打印函数调用堆栈

打印 堆栈 函数调用
2023-09-27 14:28:06 时间

有时候调试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 

执行结果: