gcc main.c -g -rdynamic
/* main.c */
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_LAYERS 20
void print_trace (void)
{
void *array[MAX_STACK_LAYERS];
size_t size;
char **strings;
size_t i;
size = backtrace (array, MAX_STACK_LAYERS);
strings = backtrace_symbols (array, size);
if (NULL == strings)
{
perror("backtrace_synbols");
exit(0);
}
printf ("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf ("%s\n", strings[i]);
free (strings);
strings = NULL;
}
void f3()
{
print_trace();
}
void f2()
{
f3();
}
void f1()
{
f2();
}
int main(char * argv[], int argc)
{
f1();
}另外,这里有一篇更加详细的:http://blog.chinaunix.net/uid-24774106-id-3457205.html
本文提供了一个使用C语言实现的堆栈跟踪示例,通过调用execinfo.h库中的backtrace()函数来获取当前运行时刻的堆栈信息。示例中定义了递归调用的函数并展示了如何打印出堆栈帧。
2205

被折叠的 条评论
为什么被折叠?



