Valgrind shows std::vector<> times of alloc is

2019-02-26 22:04发布

问题:

The code is fairly simple:

#include <vector>
int main() {
    std::vector<int> v;
}

Then I build and run it with Valgrind:

g++ test.cc && valgrind ./a.out
==8511== Memcheck, a memory error detector
==8511== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8511== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==8511== Command: ./a.out
==8511==
==8511==
==8511== HEAP SUMMARY:
==8511==     in use at exit: 72,704 bytes in 1 blocks
==8511==   total heap usage: 1 allocs, 0 frees, 72,704 bytes allocated
==8511==
==8511== LEAK SUMMARY:
==8511==    definitely lost: 0 bytes in 0 blocks
==8511==    indirectly lost: 0 bytes in 0 blocks
==8511==      possibly lost: 0 bytes in 0 blocks
==8511==    still reachable: 72,704 bytes in 1 blocks
==8511==         suppressed: 0 bytes in 0 blocks
==8511== Rerun with --leak-check=full to see details of leaked memory
==8511==
==8511== For counts of detected and suppressed errors, rerun with: -v
==8511== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

The question is two-fold:

(1) "total heap usage" indicates that there is 1 alloc and 0 free. I assume that 1 alloc is because a std::vector instance needs a memory chunk in the heap. That's fine; but why doesn't it free the memory during destruction?

(2) And, if it doesn't free it, why is there no memory leak in "LEAK SUMMARY"?

(3) By the way, what does ==8511== before each line mean? (I could've look it up in the manual, though. You don't have to answer this)

Thanks!

回答1:

Reported memory still in use by C++ runtime. You don't need to worry about it. Valgrind's FAQ has an entry regarding this problem:

First of all: relax, it's probably not a bug, but a feature. Many implementations of the C++ standard libraries use their own memory pool allocators. Memory for quite a number of destructed objects is not immediately freed and given back to the OS, but kept in the pool(s) for later re-use.



回答2:

(1) A properly implemented default constructed std::vector doesn't allocate. Esp not 72k. Try running with --leak-check=full --track-origins=yes , perhaps it shows the origin of the allocation

(2) It says it, see: still reachable. The memory is not (yet) leaked, since there's still a handle (e.g: a pointer) pointing to it.

(3) It is the process id of the application.