Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to Allocate large cpp std::vector that is less than std::vector::max_size()

I am trying to allocate a vector<bool> in c++ for 50,000,000,000 entries; however, the program errors out.terminate called after throwing an instance of ‘std::bad_alloc’
what(): std::bad_alloc
(or in the online compiler it just ends).

I initially thought this was due to too large a size; however, v1.maxsize() is greater than 50GB for me. What’s confusing though, is when I reduce the # of entries it works fine.

Question: What could be the root cause of this considering that the number of entries is less than maxsize of a vector?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Other questions/answers have suggested that similar issues are due to being on a 32 bit cpu; however I have a 64bit.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    long size = 50000000000;
    std::vector<bool> v1;

    std::cout << "max_size: " << bool(v1.max_size() > 50000000000) <<"vs" << size << "\n";
    
    v1 = std::vector<bool>(size,false);
    cout << "vector initialised \n" << endl;
    
    cout << v1.size() << endl;
        
}

note: I am essentially trying to create a memory efficient bitmap to track if certain addresses for a different data structure have been initialized. I cant use a bitset mentioned in this post since the size isn’t known at compile time.

>Solution :

From std::vector::max_size:

This value typically reflects the theoretical limit on the size of the
container, at most std::numeric_limits<difference_type>::max(). At
runtime, the size of the container may be limited to a value smaller
than max_size() by the amount of RAM available.

This means that std::vector::max_size is not a good indication to the actual maximum size you can allocate due to hardware limitation.
In practice the actual maximum size will probably be smaller, depending on your available RAM in runtime.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading