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

后端 未结 3 1441
春和景丽
春和景丽 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: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).

提交回复
热议问题