-2

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";
    }
}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Alvin Reed
  • 19
  • 3
  • Do you have 102 *gigabytes* of RAM available? – Nicol Bolas Sep 20 '21 at 13:57
  • 1
    You're probably running out of memory. `max_size` isn't doing what you think. It may be system-dependent, but at least on my testing for a single byte type vector, it returns 2^64 - 1, which is obviously way bigger than your memory can hold. – General Grievance Sep 20 '21 at 13:57

1 Answers1

1

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982