2
#include <iostream>
#include <vector>

int main(int argc, char const *argv[])
{
    std::vector<int> a(32768, 0);
    std::cout << "Size " << sizeof a << "\nCapacity " << a.capacity() << "\nElements " << a.size();
    return 0;
}

for this program im getting the output:

Size 24
Capacity 32768
Elements 32768

using valgrind i calculated heap usage which is:

132096 bytes

that is (32768 x 4 bytes) + 24 bytes

im interested in how are these 24 bytes used by vector a

g0x0
  • 93
  • 7
  • 1
    Does for example https://stackoverflow.com/questions/30422205/why-the-libc-stdvector-internally-keeps-three-pointers-instead-of-one-pointe answer your question? `that is (32768 x 4 bytes) + 24 bytes` that is... a coincidence that it's equal to that. – KamilCuk Sep 04 '21 at 20:15
  • 2
    The 24 bytes are probably implementation dependent. If you want to know more just open the header file :) And you can also lookup "small vector optimization". – Pepijn Kramer Sep 04 '21 at 20:26
  • @KamilCuk Thank you that explains it all :) – g0x0 Sep 04 '21 at 20:34
  • A vector allocates memory from the free store (usually the heap, or it is on all the platforms I currently work on). It allocates more memory when it runs out of capacity. It doesn't free extra capacity memory, unless requested. My system maintains separate heaps for `malloc`, `new`, and `new[]` ... but that's an implementation detail, which helps shake out memory management bugs. – Eljay Sep 04 '21 at 20:35

1 Answers1

3

As addressed in the comments by Kamil, a std::vector keeps track of three pointers internally. One pointer to the begin, one to end and one to the end of allocated memory (see stack post). Now, the size of a pointer should be 8 bytes on any 64-bit C/C++ compiler so, 3 * 8 bytes = 24 bytes (see wiki).

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
netlemon
  • 964
  • 8
  • 22