c++ - 有没有办法比较 C/C++ 程序的两次不同运行?

标签 c++ c debugging gdb valgrind

所以我正在调试这个我从即将毕业的博士生那里继承的程序,或者在学生完成论文后发生的任何事情。无论如何,现在我有责任调试它。该程序基本上接收几个文本文件并对其进行处理。我一直遇到的问题(段错误)是因为程序试图访问尚未初始化的数组。我想知道是否有任何调试工具可以让您运行程序,并比较程序运行的两个不同路径。我想我可以手动完成该程序,但我宁愿不这样做,因为它相当大,而且我还没有掌握它。我一直在使用 GDB 和 Valgrind(以及使用 g++ -wall 来显示警告),这就是我走到这一步的方式。但是有没有什么软件可以让你做我上面描述的事情,或者甚至只是引导你完成你的程序。

最佳答案

这些建议特定于 GCC。您可以使用 gcov覆盖率工具,用于详细了解程序的哪些部分已被执行以及执行频率。您必须将一些特殊选项传递给 GCC 才能为 gcov 生成适当的检测和输出以进行处理。

--coverage This option is used to compile and link code instrumented for coverage analysis. The option is a synonym for -fprofile-arcs -ftest-coverage (when compiling) and -lgcov (when linking). See the documentation for those options for more details.

然后,当您执行您的程序时,会生成一些分析和覆盖率数据。然后您可以调用 gcov 来分析该输出。以下是从上面的链接中获取的输出示例:

         -:    0:Source:tmp.c
         -:    0:Graph:tmp.gcno
         -:    0:Data:tmp.gcda
         -:    0:Runs:1
         -:    0:Programs:1
         -:    1:#include <stdio.h>
         -:    2:
         -:    3:int main (void)
         1:    4:{
         1:    5:  int i, total;
         -:    6:
         1:    7:  total = 0;
         -:    8:
        11:    9:  for (i = 0; i < 10; i++)
        10:   10:    total += i;
         -:   11:
         1:   12:  if (total != 45)
     #####:   13:    printf ("Failure\n");
         -:   14:  else
         1:   15:    printf ("Success\n");
         1:   16:  return 0;
         -:   17:}

如果你想实现自己的检测来记录程序的调用历史,你可以使用 -finstrument-functions及其在 GCC 上的相关选项。

-finstrument-functions
Generate instrumentation calls for entry and exit to functions. Just after function entry and just before function exit, the following profiling functions are called with the address of the current function and its call site. (On some platforms, __builtin_return_address does not work beyond the current function, so the call site information may not be available to the profiling functions otherwise.)

      void __cyg_profile_func_enter (void *this_fn,
                                     void *call_site);
      void __cyg_profile_func_exit  (void *this_fn,
                                     void *call_site);

The first argument is the address of the start of the current function, which may be looked up exactly in the symbol table.

在 C++ 中,这些 Hook 的实现应声明为 extern "C"。您可以实现 Hook 以在每次调用函数时进行记录。你没有得到函数名称,但你可以在之后使用 objdump 对指针进行后处理或 addr2line .

关于c++ - 有没有办法比较 C/C++ 程序的两次不同运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17240179/

相关文章:

c++ - 检查字符串是否作为 vector 中的元素存在

c - 访问成员结构时出现无效数字

c++ - 调试时 Visual Studio 卡住

C:什么是函数指针转换?

c++ - 将字符串相关函数从 C++ 转换为 C

javascript - 在事先不知道方法的情况下,如何在调试时找出 Javascript 中调用了哪些方法?

matlab - 退出并继续 MATLAB 调试

c++ - 如何在 C++ 中的基类和派生类之间共享公共(public)默认参数值?

c++ - QtWebPage - 多次调用 loadFinished()

c++ - static_assert 在宏中,但也扩展为可以用作函数参数的东西