Monday, November 26, 2012

Printing call stack of a function using code in C/C++

Many times when you deal with memory related issues like resolving core-dumps, you are mis-led by debuggers in call stack of the issue because of various reasons.
In those cases, you can actually write a piece of code that can print the call stack from any place. The good thing is, its fully in code, so you can identify your culprit call stack with this way by adding this code in your suspect functions.

Use this unix code snippet to print call stack:
(Dont forget to include execinfo.h header file)

void* buff[100];
int cnt=backtrace(buff,100);
char** str=backtrace_symbols(buff,cnt);
for(int i=0;i<cnt;i++)
{
printf("\n%s\n",str[i]);
}

Search more on the functions used in example to leverage more. If you have any troubles in the call stack, use -rdynamic option while compilation.

2 comments:

  1. There's a memory leak, need to call free(str).

    That memory is malloced by backtrace_symbols().

    ReplyDelete