How does the C ++ library implementation allocate memory but not free it when it exits the program?

The code is pretty simple:

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

Then I create and run it using Valgrind on Linux:

g++ test.cc && valgrind ./a.out
==8511== Memcheck, a memory error detector
...
==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== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

There is no memory leak, although there are 1 alloc and 0 for free. The answer to this question is cited by this paragraph from the Valgrind FAQ for an explanation -

Many implementations of C ++ standard libraries use their own memory pool allocators. Memory for a number of destroyed objects is not immediately freed up and returned back to the OS, but is stored in the pool (s) for subsequent reuse.

My main question is:

++? , , (a.out ), ? , , , ? , "" ?

:

71 . ?

:)

+2
3

-, vector. , gcc clang -O2 main() ( xor eax, eax . . . , vector ( gcc clang) - , , .

, ( ) ( .cpp), :

#include <vector>

void sink(std::vector<int>& v);

int main() {
    std::vector<int> v(12345678);
    sink(v);
}

, , , - .

, ~ 72 000 , , Valgrind, std::vector<int> v , , main.

, , .

, , , , . , , . Valgrind " ", , , , , , - .

, . , Valgrind malloc free , , .

, FAQ , " ", , , , malloc operator new , , , , delete (, free delete).

, ( , ). Valgrind, "" .

- std::allocator C++ , , "" - : , , . , , , allocator .

: () , , () , , .

, , , () - " ". Valgrind , , - , . "" , ( , , ), , Valgrind , , " ".,

+5

, . , . os, , .

+4

C++ ?

. valgrind , , - C++ .

, , () ?

, . Valgrind , . , , , ( !) , free. , malloc .

, , , ? , "" ?

. .

, , .

71 . ?

72 , , C++ " ". ( bad_alloc), malloc -. , , malloc bad_alloc , bad_alloc bad_alloc.

:

       // 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);

. Https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=libstdc%2B%2B-v3/libsupc%2B%2B/eh_alloc.cc;h=005c28dbb1146c28715ac69f013ae41e3492f992;b= # L117

valgrind EH , in use at exit: 72,704 bytes in 1 blocks , in use at exit: 72,704 bytes in 1 blocks. , , , ( ), , . Valgrind , . valgrind, , ( , ).

+1

Source: https://habr.com/ru/post/1683134/


All Articles