c - 在 C 程序中使用 Valgrind

标签 c ubuntu valgrind

我只是 valgrind 用法的初学者。我已经将 ubuntu 作为 vmWare 的一部分打开,我刚刚制作了一个应该显示 valgrind 错误的 c 程序,并在 a.out 上运行了 valgrind,但我无法查看输出中可见的行号: 使用的命令是:

valgrind --leak-check=full --track-origins=yes ./a.out 

对于如下所示的C程序:

  #include <stdlib.h>

  #define ARRAY_SIZE      (5)

  typedef char TEST_TYPE;


  void invalid_write(TEST_TYPE* array, int size)
  {
     array[size] = 5;
  }


 int main(void)
 {
    TEST_TYPE static_array[ARRAY_SIZE];
    TEST_TYPE* dynamic_array = NULL;
    TEST_TYPE* p = NULL;
    TEST_TYPE i;


    dynamic_array = (TEST_TYPE*)malloc(ARRAY_SIZE * sizeof(TEST_TYPE));
   /* ERROR 1 : Writing out of array boundaries (heap overrun) */
    invalid_write(dynamic_array, ARRAY_SIZE);
 }

输出如下所示:

==6801== Memcheck, a memory error detector
==6801== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==6801== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==6801== Command: ./a.out
==6801== 
==6801== Invalid write of size 1
==6801==    at 0x80483ED: invalid_write (in /home/jci/a.out)
==6801==    by 0x804842E: main (in /home/jci/a.out)
==6801==  Address 0x419702d is 0 bytes after a block of size 5 alloc'd
==6801==    at 0x4026444: malloc (vg_replace_malloc.c:263)
==6801==    by 0x8048416: main (in /home/jci/a.out)
==6801== 
==6801== 
==6801== HEAP SUMMARY:
==6801==     in use at exit: 5 bytes in 1 blocks
==6801==   total heap usage: 1 allocs, 0 frees, 5 bytes allocated
==6801== 
==6801== 5 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6801==    at 0x4026444: malloc (vg_replace_malloc.c:263)
==6801==    by 0x8048416: main (in /home/jci/a.out)
==6801== 
==6801== LEAK SUMMARY:
==6801==    definitely lost: 5 bytes in 1 blocks
==6801==    indirectly lost: 0 bytes in 0 blocks
==6801==      possibly lost: 0 bytes in 0 blocks
==6801==    still reachable: 0 bytes in 0 blocks
==6801==         suppressed: 0 bytes in 0 blocks
==6801== 
==6801== For counts of detected and suppressed errors, rerun with: -v
==6801== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 11 from 6)

我应该如何获得这些错误的行号,以便我们可以准确地查明问题所在?目前使用的valgrind版本是3.7.0。

最佳答案

您需要使用调试信息构建程序,对于 gcc,您应该能够执行如下操作:

gcc -g -O0 -Wall sourcefile.c

然后 Valgrind 会显示源代码中的行号和函数名称。

关于c - 在 C 程序中使用 Valgrind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15569582/

相关文章:

c - 错误 : assignment makes integer from pointer without a cast [-Werror] str1 = (unsigned char*)s1

c++ - Eclipse PTP OpenMPI 并行运行/调试

c - pthread 条件信号与 POSIX 实时信号相同还是不同?

c++ - Ubuntu 上的 Qt+OpenCV 无法运行/调试 : Failed to start application

linux - gitlab 8.2.0 git 不工作

homebrew - 在 macOS High Sierra 10.13.2 上使用 brew 安装 valgrind

c - 为什么 Valgrind memcheck 不捕获这个 UB?

代码存储器和数据存储器

linux - 如何在 Ubuntu 上的文件中使用逻辑 AND 条件搜索关键字?

c - 为什么我的程序会自动释放东西?