在64位系统中分配超过4GB的内存
Allocating more than 4GB memory in a 64 bit system
我正在32GB的Windows Server 2008 R2上运行这段在64位vc++2005上编译的代码。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是32位:这意味着您的最大值是2147483647,sizeof(double)*536870912>=214783647。(我真的不知道这是否有道理。这可能取决于买办的工作方式)
- 您的分配失败
我建议你测试以下代码:
#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的单个块。
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 为什么示例代码访问IUnknown中已删除的内存
- 如何在C++类内存结构中创建"spacer"?
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- x64 进程可以在 4GB RAM 上占用多少内存
- 在64位系统中分配超过4GB的内存
- 强制内存分配从 64 位 Linux 上的较高地址 (>4GB) 分配
- 在C++中,将大型二进制(1GB-4GB)文件加载到内存中的最快方法是什么
- 你能用 c 或 c++ 分配一个非常大的单块内存(> 4GB)吗?