Max number of elements vector

Viewed 93

I was looking to see how many elements I can stick into a vector before the program crashes. When running the code below the program crashed with a bad alloc at i=90811045, aka when trying to add the 90811045th element. My question is: Why 90811045?

it is:

  • not a power of two
  • not the value that vector.max_size() gives
  • the same number both in debug and release
  • the same number after restarting my computer
  • the same number regardless of what the value of the long long is

note: I know I can fix this by using vector.reserve() or other methods, I am just interested in where 90811045 comes from.

code used:

#include <iostream>
#include <vector>

int main() {
    std::vector<long long> myLongs;

    std::cout << "Max size expected : " << myLongs.max_size() << std::endl;
    for (int i = 0; i < 160000000; i++) {
        myLongs.push_back(i);

        if (i % 10000 == 0) {
            std::cout << "Still going!      : " << i << "   \r";
        }
    }

    return 0;
}

extra info: I am currently using 64 bit windows with 16 GB of ram.

1 Answers

Why 90811045?

It's probably just incidental.

That vector is not the only thing that uses memory in your process. There is the execution stack where local variables are stored. There is memory allocated by for buffering the input and output streams. Furthermore, the global memory allocator uses some of the memory for bookkeeping.

90811044 were added succesfully. The vector implementation (typically) has a deterministic strategy for allocating larger internal buffer. Typically, it multiplies the previous capacity by a constant factor (greater than 1). Hence, we can conclude that 90811044 * sizeof(long long) + other_usage is consistently small enough to be allocated successfully, but (90811044 * sizeof(long long)) * some_factor + other_usage is consistently too much.

Related