I need to create a very big array in my project. I tried 3 methods, but all of them turned out to be bad_alloc
. I couldn't understand, as my PC's RAM is 10GB.
Here are my implementations under MSVC2015 x86 mode.
CODE1
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
MyClass *mc = new MyClass[MEM_SIZE / sizeof(MyClass)];
cout << "done!" << endl;
return 0;
}
CODE2
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
vector<MyClass> myv;
myv.resize(MEM_SIZE / sizeof(MyClass));
cout << "done!" << endl;
return 0;
}
CODE3
#include<fstream>
#include<iostream>
#include<string>
#include<vector>
using namespace std;
const long long MEM_SIZE = 1LL * 1024LL * 1024LL * 1024LL; // available memory 1GB
typedef struct MyClass {
int a;
unsigned char b,c,d;
size_t e,f;
double g, h;
};
int main() {
vector<MyClass> myv;
MyClass tmp;
for (int i = 0; i < 12000000; i++){
tmp.a = i;
myv.push_back(tmp);
}
cout << "done!" << endl;
return 0;
}
The size of MyClass
is 32 Bytes, I set available memory as 1GB, so the array length is 1GB/32B=33554432.
As for CODE1 and CODE2, the array size is 1GB, far less than PC's RAM, why bad_alloc
?
As for CODE3, I know when push_back
, the capacity of vector will double, but it's also less than PC's RAM. In CODE3, when i==11958657
crashed.
But when I build and run in x64 mode, all are fine. To my knowledge, x86's heap is around 2GB, why my 1GB array crashed?
How do i do in x86 mode?