【问题标题】:Allocating more than 4GB memory in a 64 bit system在 64 位系统中分配超过 4GB 的内存
【发布时间】:2013-07-30 22:28:56
【问题描述】:

我正在运行此代码,在 64 位 vc++ 2005 上编译,在 32GB 的 Windows Server 2008 R2 上。 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 在 64 位 Windows 上是 32 位,所以循环永远不会终止。您应该将i 的类型更改为size_t,以确保它对于任何数组索引都足够大。不过,我不知道这是否是唯一的问题。
  • 电脑内存足够,不代表可以在里面找到一个空闲的4GB连续块。
  • @MikeSeymour 即便如此,即使是 32 位整数,5 亿多一点也不成问题。
  • 536870912 * sizeof(double) 为我产生 0。看起来像 operator new 内部的环绕。
  • @KirkBackus new 不会返回 null 除非使用这里不是这种情况的 nothrow 版本?

标签: c++ memory windows-server-2008-r2 access-violation


【解决方案1】:

可能是以下问题之一:

  • long int 是 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 的块。

【讨论】:

    猜你喜欢
    • 2011-08-20
    • 2021-04-10
    • 1970-01-01
    • 2015-10-23
    • 2018-10-22
    • 1970-01-01
    • 2012-12-02
    • 2013-05-04
    • 2013-03-25
    相关资源
    最近更新 更多