在 64 位系统中分配超过 4GB 的内存 [英] Allocating more than 4GB memory in a 64 bit system
本文介绍了在 64 位系统中分配超过 4GB 的内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 32GB 的 Windows Server 2008 R2 上运行在 64 位 vc++ 2005 上编译的代码.for 循环内部存在访问冲突.
I'm running this code, compiled on 64 bits vc++ 2005, on Windows Server 2008 R2 with 32GB. There is an access violation inside the for loop.
#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] 中没有异常,为什么在对特定数组位置进行赋值时会出现访问冲突?
So if there is no exception in new double[536870912], why am I getting an access violation when doing an assignment over a particular array position?
还有一点值得一提的是,这个程序在另一台电脑上测试成功.
Another point worth mentioning is that this program was succesfully tested on another computer.
推荐答案
可能是以下问题之一:
- 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 的单个块.
Editing: Using this code, i just achieved allocate a single block of 9GB.
这篇关于在 64 位系统中分配超过 4GB 的内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文