Linux_打印函数调用栈
方法一:
- #include <stdio.h>
- #include <stdlib.h>
- #include <execinfo.h>
- /* Obtain a backtrace and print it to stdout. */
- void
- print_trace (void)
- {
- void *array[10];
- size_t size;
- char **strings;
- size_t i;
- size = backtrace (array, 10);
- strings = backtrace_symbols (array, size);
- printf ("Obtained %zd stack frames.\n", size);
- for (i = 0; i < size; i++)
- printf ("%s\n", strings);
- free (strings);
- }
- int main()
- {
- print_trace ();
- }
编译:g++ stack.c -g -o stack -rdynamic
方法二:
- #include <unistd.h>
- #include <stdio.h>
- #include <execinfo.h>
- #include <stdlib.h>
- #include <string.h>
- void backtrace()
- {
- const int maxLevel = 200;
- void* buffer[maxLevel];
- int level = backtrace(buffer, maxLevel);
- const int SIZE = 1024;
- char cmd[SIZE] = "addr2line -C -f -e ";
- // let prog point to the end of "cmd"
- char* prog = cmd + strlen(cmd);
- int r = readlink("/proc/self/exe", prog, sizeof(cmd) - (prog-cmd)-1);
- FILE* fp = popen(cmd, "w");
- if (!fp)
- {
- perror("popen");
- return;
- }
- for (int i = 0; i < level; ++i)
- {
- fprintf(fp, "%p\n", buffer[i]);
- }
- fclose(fp);
- }
- void foo(int, char*)
- {
- backtrace();
- }
- void bar(double)
- {
- foo(0, NULL);
- }
- int main()
- {
- bar(0.0);
- //A a;
- return 0;
- }
编译:g++ stack1.c -g -o stack1 -rdynamic
阅读(1124) | 评论(0) | 转发(0) |