http://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c

There's backtrace(), and backtrace_symbols():

From the man page:

  1. #include <execinfo.h>
  2. #include <stdio.h>
  3. ...
  4. void* callstack[];
  5. int i, frames = backtrace(callstack, );
  6. char** strs = backtrace_symbols(callstack, frames);
  7. for (i = ; i < frames; ++i) {
  8. printf("%s\n", strs[i]);
  9. }
  10. free(strs);
  11. ...

One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:

  1. class MyException : public std::exception {
  2.  
  3. char ** strs;
  4. MyException( const std::string & message ) {
  5. int i, frames = backtrace(callstack, );
  6. strs = backtrace_symbols(callstack, frames);
  7. }
  8.  
  9. void printStackTrace() {
  10. for (i = ; i
  11. ......
  12. try {
  13. throw MyException("Oops!");
  14. } catch ( MyException e ) {
  15. e.printStackTrace();
  16. }

提示,最好把编译优化去掉,不然打印可能不准确。

http://www.gnu.org/software/libc/manual/html_node/Backtraces.html

A backtrace is a list of the function calls that are currently active in a thread. The usual way to inspect a backtrace of a program is to use an external debugger such as gdb. However, sometimes it is useful to obtain a backtrace programmatically from within a program, e.g., for the purposes of logging or diagnostics.

The header fileexecinfo.hdeclares three functions that obtain and manipulate backtraces of the current thread.

Function: int backtrace (void **buffer, int size)

Preliminary: | MT-Safe | AS-Unsafe init heap dlopen plugin lock | AC-Unsafe init mem lock fd | See POSIX Safety Concepts.

The backtrace function obtains a backtrace for the current thread, as a list of pointers, and places the information into buffer. The argument size should be the number of void * elements that will fit into buffer. The return value is the actual number of entries of buffer that are obtained, and is at most size.

The pointers placed in buffer are actually return addresses obtained by inspecting the stack, one return address per stack frame.

Note that certain compiler optimizations may interfere with obtaining a valid backtrace. Function inlining causes the inlined function to not have a stack frame; tail call optimization replaces one stack frame with another; frame pointer elimination will stop backtrace from interpreting the stack contents correctly.

Function: char ** backtrace_symbols (void *const *buffer, int size)

Preliminary: | MT-Safe | AS-Unsafe heap | AC-Unsafe mem lock | See POSIX Safety Concepts.

The backtrace_symbols function translates the information obtained from the backtrace function into an array of strings. The argument buffer should be a pointer to an array of addresses obtained via the backtrace function, and size is the number of entries in that array (the return value of backtrace).

The return value is a pointer to an array of strings, which has size entries just like the array buffer. Each string contains a printable representation of the corresponding element of buffer. It includes the function name (if this can be determined), an offset into the function, and the actual return address (in hexadecimal).

Currently, the function name and offset only be obtained on systems that use the ELF binary format for programs and libraries. On other systems, only the hexadecimal return address will be present. Also, you may need to pass additional flags to the linker to make the function names available to the program. (For example, on systems using GNU ld, you must pass (-rdynamic.)

The return value of backtrace_symbols is a pointer obtained via the malloc function, and it is the responsibility of the caller to free that pointer. Note that only the return value need be freed, not the individual strings.

The return value is NULL if sufficient memory for the strings cannot be obtained.

Function: void backtrace_symbols_fd (void *const *buffer, int size, int fd)

Preliminary: | MT-Safe | AS-Safe | AC-Unsafe lock | See POSIX Safety Concepts.

The backtrace_symbols_fd function performs the same translation as the function backtrace_symbols function. Instead of returning the strings to the caller, it writes the strings to the file descriptor fd, one per line. It does not use the malloc function, and can therefore be used in situations where that function might fail.

The following program illustrates the use of these functions. Note that the array to contain the return addresses returned by backtrace is allocated on the stack. Therefore code like this can be used in situations where the memory handling via malloc does not work anymore (in which case the backtrace_symbols has to be replaced by a backtrace_symbols_fd call as well). The number of return addresses is normally not very large. Even complicated programs rather seldom have a nesting level of more than, say, 50 and with 200 possible entries probably all programs should be covered.

  1. #include <execinfo.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. /* Obtain a backtrace and print it to stdout. */
  6. void
  7. print_trace (void)
  8. {
  9. void *array[];
  10. size_t size;
  11. char **strings;
  12. size_t i;
  13.  
  14. size = backtrace (array, );
  15. strings = backtrace_symbols (array, size);
  16.  
  17. printf ("Obtained %zd stack frames.\n", size);
  18.  
  19. for (i = ; i < size; i++)
  20. printf ("%s\n", strings[i]);
  21.  
  22. free (strings);
  23. }
  24.  
  25. /* A dummy function to make the backtrace more interesting. */
  26. void
  27. dummy_function (void)
  28. {
  29. print_trace ();
  30. }
  31.  
  32. int
  33. main (void)
  34. {
  35. dummy_function ();
  36. return ;
  37. }

c语音中打印参数调用层级即call stack, call trace的更多相关文章

  1. JAVA学习笔记--方法中的参数调用是引用调用or值调用

    文献来源:<JAVA核心技术卷Ⅰ>,第4章第5节 (没有相关书籍的可看传送门) ps:测试demo因为偷懒,用的是String对象 结论:Java使用的是对象的值引用.即将任何对象所在内存 ...

  2. unity 如何在botton AddListen中传递参数调用函数

    使用Deleget方法包含该函数即可. levelItem.GetComponent<Toggle().onValueChanged.AddListener(SetSelectedLevel(l ...

  3. 描述了say_hello函数的具体内容,调用zend_printf系统函数在php中打印字符串

    下载一个php的源代码包,这里使用的是php 4.0.5版,解压后会看到php的根目录下会有README.EXT_SKEL这样一个文件,打开详细阅读了一下,发现了一个非常好用的工具,这个工具可以帮你构 ...

  4. Liferay中SQL打印参数

      XX\tomcat-7.0.42\webapps\ROOT\WEB-INF\classes\log4j.properties log4j.rootLogger=INFO, CONSOLE log4 ...

  5. 程序中打印当前进程的调用堆栈(backtrace)

    为了方便调式程序,产品中需要在程序崩溃或遇到问题时打印出当前的调用堆栈.由于是基于Linux的ARM嵌入式系统,没有足够的空间来存放coredump文件. 实现方法,首先用__builtin_fram ...

  6. 在go中通过cmd调用python命令行参数量级过大问题解决

    问题描述如下: 在go中使用cmd调用python命令行 cmd := exec.Command("python", "dimine/Kriging/matrix.py& ...

  7. Tom_No_02 Servlet向流中打印内容,之后在调用finsihResponse,调用上是先发送了body,后发送Header的解释

    上次在培训班学上网课的时候就发现了这个问题,一直没有解决,昨天又碰到了,2-3小时也未能发现点端倪,今早又仔细缕了下,让我看了他的秘密 1.Servlet向流中打印内容,之后在调用finsihResp ...

  8. vlc 详细使用方法:libvlc_media_add_option 函数中的参数设置

    vlc 详细使用方法:libvlc_media_add_option 函数中的参数设置 [转载自]tinyle的专栏 [原文链接地址]http://blog.csdn.net/myaccella/ar ...

  9. UIViewController中各方法调用顺序及功能详解

    UIViewController中各方法调用顺序及功能详解 UIViewController中loadView, viewDidLoad, viewWillUnload, viewDidUnload, ...

随机推荐

  1. php中getimagesize函数的用法

    php获取图片信息getimagesize,php自带函数.获取图片的类型,尺寸的方法有许多,该函数仅是方法之一. getimagesize() 函数将测定任何 GIF,JPG,PNG,SWF,SWC ...

  2. linux 配置apache+subversion

    http://apr.apache.org/download.cgi http://subversion.tigris.org/servlets/ProjectDocumentList?folderI ...

  3. 启动Tomcat出现Using CATALINA_BASE

    有一次命令行启动Tomcat的时候,出现: Using CATALINA_BASE: "D:\apache-tomcat-6.0.35"Using CATALINA_HOME: & ...

  4. iOS --- 取整数

    Objective-C拓展了C,自然很多用法是和C一致的.比如浮点数转化成整数,就有以下四种情况. 1.简单粗暴,直接转化 float f = 1.5; int a; a = (int)f; NSLo ...

  5. 五子棋-b

    五子棋是程序猿比较熟悉的一款小游戏,相信很多人大学时期就用多种语言写过五子棋小游戏.笔者工作闲暇之余,试着用OC实现了一下,在这里给大家分享一下.有不足之处,欢迎大家提供建议和指点!!!GitHub源 ...

  6. QT5.4 计算器程序 打包&发布,解决dll的最新解决方案

    QT写界面还是很不错,就是打包会比较麻烦,折腾了一天总算是打包完成了. QT软件的打包发布一个难点是必备dll文件的识别,现在高版本QT自带了一个windeployqt工具,直接会把需要的dll生成一 ...

  7. python多线程threading.Lock锁用法实例

    本文实例讲述了python多线程threading.Lock锁的用法实例,分享给大家供大家参考.具体分析如下: python的锁可以独立提取出来 mutex = threading.Lock() #锁 ...

  8. SQL Server 2005 版本的操作系统兼容性详细列表

    操作系统要求(32 位) 此表显示对于每种 32 位版本的 SQL Server 2005,操作系统是否可以运行其服务器软件. 有关如何在 Windows Server 2008 上安装 SQL Se ...

  9. ArrayList与LinkedList实现比较

    1.ArrayList实现是基于数组来实现的,这可由ArrayList的源码看出: public class ArrayList<E> extends AbstractList<E& ...

  10. Android 如何把一个 RelativeLayout或ImageView背景设为透明

    在项目中,需要把RelativeLayout 和  ImageView背景设置为透明,怎么实现呢?这里主要通过代码,请参阅以下关键代码: public ImageView imgDetail; pri ...