zoukankan      html  css  js  c++  java
  • 打印函数调用堆栈

    有时候调试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!
    ");
    10 
    11     int nptrs;
    12     void *buffer[100];
    13     char **strings;
    14 
    15     nptrs = backtrace(buffer, 10);
    16     printf("backtrace returned %d address
    ", nptrs);
    17     strings = backtrace_symbols(buffer, nptrs);
    18     for (int j = 0; j < nptrs; ++j)
    19     {
    20         printf("%s
    ", 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 

    执行结果:

  • 相关阅读:
    【redis】--安全
    【redis】-- 数据备份和恢复
    2018.2.8 cf
    寒假零碎的东西 不定时更新补充.......
    hdu 1018
    2018寒假acm训练计划
    UVAlive 7466
    母函数
    简单数学题(水的不能在水的题了)
    随便写写的搜索
  • 原文地址:https://www.cnblogs.com/lit10050528/p/6056283.html
Copyright © 2011-2022 走看看