在64位系统中分配超过4GB的内存

Allocating more than 4GB memory in a 64 bit system

本文关键字:4GB 内存 分配 64位 系统      更新时间:2023-10-16

我正在32GB的Windows Server 2008 R2上运行这段在64位vc++2005上编译的代码。for循环内部存在访问冲突。

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{   
    double *x = new double[536870912];
    cout << "memory allocated" << endl;
    for(long int i = 0; i < 536870912; i++)
    {   
        cout << i << endl;
        x[i] = 0;
    }
    delete [] x;
    return 0;
}

所以,如果new double[536870912]中没有异常,为什么在对特定数组位置进行赋值时会出现访问冲突?

另一点值得一提的是,该程序已在另一台计算机上成功测试。

这可能是以下问题之一:

  • long int是32位:这意味着您的最大值是2147483647,sizeof(double)*536870912>=214783647。(我真的不知道这是否有道理。这可能取决于买办的工作方式)
  • 您的分配失败

我建议你测试以下代码:

#include<conio.h>
#include <iostream>
using namespace std;
#define MYTYPE unsigned long long

int main(int argc, char* argv[])
{   
    // Test compiling mode
    if (sizeof(void*) == 8) cout << "Compiling 64-bits" << endl;
    else cout << "Compiling 32-bits" << endl;
    // Test the size of mytype
    cout << "Sizeof:" << sizeof(MYTYPE) << endl;
    MYTYPE len;
    // Get the number of <<doubles>> to allocate
    cout << "How many doubles do you want?" << endl;
    cin >> len;
    double *x = new (std::nothrow) double[len];
    // Test allocation
    if (NULL==x)
    {
        cout << "unable to allocate" << endl;
        return 0;
    }
    cout << "memory allocated" << endl;
    // Set all values to 0
    for(MYTYPE i = 0; i < len; i++)
    {   
        if (i%100000==0) cout << i << endl;
        x[i] = 0;
    }
    // Wait before release, to test memory usage
    cout << "Press <Enter> key to continue...";
    getch();
    // Free memory.
    delete [] x;
}

编辑:使用这段代码,我刚刚实现了分配9GB的单个块。