为什么bad_alloc在新数组,调整大小向量和push_back到向量?

时间:2016-03-05 15:02:24

标签: c++ memory-management vector bad-alloc

我需要在项目中创建一个非常大的数组。我尝试了3种方法,但结果都是bad_alloc。我无法理解,因为我的PC的RAM是10GB。

以下是我在MSVC2015 x86模式下的实现。

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;
}

MyClass的大小为32字节,我将可用内存设置为1GB,因此数组长度为1GB / 32B = 33554432。

对于CODE1和CODE2,阵列大小为1GB,远小于PC的RAM,为什么bad_alloc

至于CODE3,我知道在push_back时,矢量的容量会加倍,但它也会比PC的RAM少。在CODE3中,当i==11958657崩溃时。

但是当我在x64模式下构建和运行时,一切都很好。据我所知,x86的堆大约是2GB,为什么我的1GB阵列崩溃了?

我如何在x86模式下进行操作?

1 个答案:

答案 0 :(得分:1)

数组必须在内存中连续,因此您不需要1 GB的内存,而是需要在一个块中。即使你有足够的可用虚拟内存(物理内存并不重要),内存碎片可能会阻止这种分配。

相关问题