bad_alloc error for std::vector resize on 64-bit. It seems to be limiting it to 32 bits

242 Views Asked by At

Why do I get bad_alloc error?

It appears to be limiting me to 32 bits but it is a 64 bit machine and compiler. I am using this to store large sets of data which are in the vector int array. I tried setting heap and stack during compiling but this did not seem to affect the bad_alloc.

#include<iostream>  
#include<vector>
//set vector with large array of integers
struct Fld               
{
    int array[256];
};
std::vector <Fld> fld;
int main()
{
    std::cout << fld.max_size() << "\n";
    int length = 100000000;
    try
    {
       //show maximum vector array size
        std::cout << fld.max_size() << "\n";
        std::cout << "resize [" << length << "]\n";
        //resize to size larger than 32 bit
        fld.resize(length);
        std::cout << "good\n";
    }
    catch(std::bad_alloc& ba)
    {
        std::cout << "bad_alloc caught: " <<  ba.what() << "\n";
    }
}
1

There are 1 best solutions below

1
Nicol Bolas On

You are limited by the amount of storage available. You attempted to allocation ~102 gigabytes of storage (each Fld is 1KB). Most systems won't let you do that.

max_size is a theoretical maximum imposed by the size of the data structure in question. It's not a promise that your computer has that much storage.