2013-07-30 9 views
7

私はこのコードを64ビットvC++ 2005、32GBのWindows Server 2008 R2でコンパイルしています。 forループ内にアクセス違反があります。 [536870912]新しいダブルでも例外がない場合、特定の配列位置を超える割り当てを行う際64ビットシステムで4GB以上のメモリを割り当てる

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

だから、なぜ私は、アクセス違反を取得していますか?

もう1つ言及しておきたいことは、このプログラムが別のコンピュータで正常にテストされたことです。

+1

過剰なコミットが原因である可能性があります。 – syam

+6

1つの問題は、64ビットWindowsでは 'long int'が32ビットなので、ループは決して終了しないということです。 'i'の型を' size_t'に変更して、どの配列のインデックスにも十分な大きさにする必要があります。しかし、それが唯一の問題かどうかはわかりません。 –

+0

何百もの数字を印刷してアクセス違反があるので、制限に達していないようです。 – Jordi

答えて

3

それはおそらく、次のような問題の一つである:

  • long int型は32ビットである:それは意味あなたの最大値は2147483647で、およびsizeof(ダブル)* 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; 

} 

編集:このコードを使用して、私はちょうど達成が9ギガバイトの単一のブロックを割り当てます。

関連する問題