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

7

我正在运行这段代码,它是在64位VC++ 2005上编译的,在安装有32GB内存的Windows Server 2008 R2上运行。在循环中出现了访问冲突。

#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]中没有异常,为什么在对特定数组位置进行赋值时会出现访问冲突?

另一个值得一提的点是该程序在另一台电脑上已经成功测试过。


6
一个问题是(我认为)在64位的Windows系统中,long int 是32位的,所以循环永远不会终止。你应该将 i 的类型更改为 size_t,以确保它足够大来表示任何数组索引。虽然我不知道这是唯一的问题。 - Mike Seymour
5
仅仅因为计算机内存足够,不意味着它能在其中找到一个自由的4GB连续块。 - Kirk Backus
5
即便如此,对于一个32位整数来说,5亿多一点应该也不是问题。 - Some programmer dude
3
536870912 * sizeof(double) 让我得到了 0。看起来是 operator new 内部有一次溢出了。 - jrok
4
@KirkBackus 的代码中,除非使用了不抛出异常版本的 new(nothrow),否则 new 操作符不会返回 null,而这里并不是使用了该版本的 new。 - stijn
显示剩余30条评论
1个回答

3

可能是以下问题之一:

  • 长整型为32位:这意味着您的最大值为2147483647,而sizeof(double)*536870912>= 2147483647。(我真的不知道这是否有意义。这可能取决于编译器的工作方式)
  • 您的分配失败了。

我建议您测试以下代码:

#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的单个块。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接