2

在工作中,我正在用 C 语言编写一个相当复杂的软件,并且我经常使用 valgrind 对其进行测试。到目前为止,该程序运行良好,没有内存泄漏或数组边界违规,并且在 valgrind 报告中,“frees”的数量与“mallocs”的数量相匹配 - 很棒。让我烦恼的是它报告了数千个 free 和 malloc。而且我知道一个事实我做的不超过50-60。我确实知道,当我的程序调用“fopen”时,valgrind 会将调用计入 malloc 的数量,同样,“fclose”也会计入“frees”的数量。但就我而言,这仍然不能解释我看到的内存被分配和释放多少次的数字。我仔细搜索了我的代码以寻找罪魁祸首,但我一无所获。我可以' 出于明显的原因,我不会在此处发布任何代码,但我只想知道,我是否遗漏了什么?是否还有其他 C 操作使 valgrind 计入 malloc 和 free 的数量?

这是我的 valgrind 报告。如您所见,从这个角度来看,一切看起来都很好。

Memcheck, a memory error detector
Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
Command: ./Codec
Parent PID: 3526

HEAP SUMMARY:
     in use at exit: 0 bytes in 0 blocks
   total heap usage: 2,407 allocs, 2,407 frees, 28,877,748 bytes allocated

 All heap blocks were freed -- no leaks are possible

 For counts of detected and suppressed errors, rerun with: -v
 ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)
4

2 回答 2

0

Remember that there's many function calls that could allocate memory, strdup, fopen, creating threads, loading shared objects, parsing timezone or locale information (as a time related function could require), 3.d party libraries could allocate memory in a number of ways, and so on.

But, run your program with the valgrind massif tool, http://valgrind.org/docs/manual/ms-manual.html (read those docs)

e.g.

 valgrind --depth=20  --tool=massif ./Calc

This produces a massif.out.XXX file which shows you various sources of allocations, and the snapshot of the heap, e.g. as an excerpt:

snapshot=9
#-----------
time=137984
mem_heap_B=640
mem_heap_extra_B=40
mem_stacks_B=0
heap_tree=peak
n2: 640 (heap allocation functions) malloc/new/new[], --alloc-fns, etc.
 n1: 352 0x4BFD095A: __fopen_internal (in /usr/lib/libc-2.17.so)
  n1: 352 0x4BFD0A39: fopen@@GLIBC_2.1 (in /usr/lib/libc-2.17.so)
   n0: 352 0x8048784: main (tailq_example.c:63)
 n5: 288 0x8048580: add_block (tailq_example.c:20)
  n0: 72 0x8048748: main (tailq_example.c:60)
  n0: 72 0x804875C: main (tailq_example.c:61)
  n0: 72 0x80487DC: main (tailq_example.c:72)
  n0: 72 0x80487F0: main (tailq_example.c:73)
  n0: 0 in 1 place, below massif's threshold (01.00%)
于 2013-10-18T12:36:27.087 回答
0

好吧,如果您调用执行 malloc 和 free 调用的库函数,您将看到很多分配和释放。一些库函数、执行分配的系统调用是 strdup、pthread_create、timer_create 等

于 2013-10-18T10:11:30.077 回答