跟踪断言失败时如何知道调用函数

use*_*260 13 c++ function

我的问题是与此相关的SO职位和其他一些人的一致好评.我想知道调用函数的名称,因为在断言失败时,我不知道哪个函数向被调用者传递了一个垃圾值.一种方法是检查所有可以调用此函数的函数,但这非常麻烦.

你能建议一个更好的解决方案,即使平台依赖吗?我正在使用g ++ 4.6.提前致谢.

Man*_*ish 8

backtrace()

例如

#include <execinfo.h>
#include <stdio.h>

void bar() {
  void* callstack[128];
  int i, frames = backtrace(callstack, 128);
  char** strs = backtrace_symbols(callstack, frames);
  for (i = 0; i < frames; ++i) {
    printf("%s\n", strs[i]);
  }
  free(strs);
}

int foo() {
  bar();
  return 0;
}

int main() {
  foo();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0   a.out                               0x0000000100000e24 bar + 28
1   a.out                               0x0000000100000e81 foo + 14
2   a.out                               0x0000000100000e96 main + 14
3   a.out                               0x0000000100000e00 start + 52
4   ???                                 0x0000000000000001 0x0 + 1
Run Code Online (Sandbox Code Playgroud)

看:

当我的 gcc C++ 应用程序崩溃时如何生成堆栈跟踪


Cor*_*ren 5

你在glibc中有回溯函数.它可以让您使用调用函数或方法进行完整跟踪.

如果你只是想调用者,这里还有特定的功能GCC只是这样的:

__builtin_frame_address(int level);
Run Code Online (Sandbox Code Playgroud)

有了level == 1你的来电功能.有关如何使用它的更多详细信息,请参阅此文章.

以下是文档中的示例程序:

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.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[i]);

  free (strings);
}

/* A dummy function to make the backtrace more interesting. */
void
dummy_function (void)
{
  print_trace ();
}

int
main (void)
{
  dummy_function ();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)