簡體   English   中英

在64位系統中分配超過4GB的內存

[英]Allocating more than 4GB memory in a 64 bit system

我正在運行此代碼,在64位vc ++ 2005上編譯,在Windows Server 2008 R2上使用32GB。 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;
}

因此,如果新雙[536870912]中沒有異常,為什么在對特定陣列位置進行賦值時會出現訪問沖突?

值得一提的另一點是,該程序在另一台計算機上成功測試。

這可能是以下問題之一:

  • long int是32位:這意味着你的最大值是2147483647,而sizeof(double)* 536870912> = 2147483647.(我真的不知道這是否有意義。它可能取決於compiller如何工作)
  • 你的分配失敗了。

我建議你測試下面的代碼:

#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的塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM