Valgrind shows std::vector<> times of alloc is more than free, but no memory leak

后端 未结 3 1437
春和景丽
春和景丽 2021-01-20 22:29

The code is fairly simple:

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

Then I build and run it with Valgrind:

相关标签:
3条回答
  • 2021-01-20 22:48

    (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.

    0 讨论(0)
  • 2021-01-20 22:51

    The 72kb you're seeing is allocated by the C++ runtime for its "emergency exception-handling pool". This pool is used to be able to allocate exception objects (such as bad_alloc exceptions) even when malloc can no longer allocate anything. We pre-allocate at startup, so if malloc runs out of memory we can still throw bad_alloc exceptions.

    The specific number comes from this code:

           // Allocate the arena - we could add a GLIBCXX_EH_ARENA_SIZE environment
           // to make this tunable.
           arena_size = (EMERGENCY_OBJ_SIZE * EMERGENCY_OBJ_COUNT
                         + EMERGENCY_OBJ_COUNT * sizeof (__cxa_dependent_exception));
           arena = (char *)malloc (arena_size);
    

    See https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/libsupc%2B%2B/eh_alloc.cc;h=005c28dbb1146c28715ac69f013ae41e3492f992;hb=HEAD#l117

    Newer versions of valgrind know about this emergency EH pool and call a special function to free it right before the process exits, so that you don't see in use at exit: 72,704 bytes in 1 blocks. This was done because too many people fail to understand that memory still in use (and still reachable) is not a leak, and people kept complaining about it. So now valgrind frees it, just to stop people complaining. When not running under valgrind the pool doesn't get freed, because doing so is unnecessary (the OS will reclaim it when the process exits anyway).

    0 讨论(0)
  • 2021-01-20 22:52

    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.

    0 讨论(0)
提交回复
热议问题