Default size of std::vector / Programming books myth?
c++, containers, memory-management, stl, vector
Solution
The book is incorrect in several ways. `std::vector` grows according to a geometric series, so a certain percentage will always be filled (unless you `erase` elements). The clippings may add up, but in general it will be a fraction proportional to the memory actually used. 50-65% is a typical worst case lower bound for the fraction that is actually in use.
This is not implementation dependent. The geometric series is required to ensure that `push_back` takes O(1) amortized time. Linear growth would result in O(N) amortized time (or O(N^2) to `push_back` a sequence of N values).
The implementation may decide a non-negligible minimum size for a non-empty `vector`, but there's no good reason to do so because small ones are common. Likewise, default-initialized vectors are invariably implemented to reserve no dynamic memory at all.
You don't need `malloc_size` to learn how much memory is being reserved. Just use `v.capacity()` `* sizeof( elem_type )`.
Problem
in a german programming book(dating to 2012) called "C++ für C-Programmierer"(C++ for C programmers, duh!) which I bought as a reference I found the following section in the chapter about the STL(I'll translate right away for you guys): Most STL implementations are generous in terms of memory management. The allocation of vectors is mostly done in 1kb chunks for instances. The clipppings do not really matter if one allocates a few vectors, but it does if you create ten- to hundredthousands of them. I could not find any source confirming that. I know it depends on the implementation, but I could not find anything that confirms that for even one platform. Cplusplus.com merely states: [...] Therefore, compared to arrays, vectors consume more memory in exchange for the ability to manage storage and grow dynamically in an efficient way. What have I tried so far? I wrote a little C++ program exploiting the OS X specific malloc_size() function, but I have never used it and I am pretty sure I am doing it wrong. If I do something along the lines of: ``` std::vector<int>* i = new std::vector<int>; std::cout << malloc_size(i) << std::endl; ``` Cout merely tells me `32`, which may well be the size of an int and therefore prove the author partially wrong, but I am not really convinced by my own efforts. Does anyone know better or know a resource? Thanks in advance. Regards, Carson