#include <iostream>
using namespace std;
int main()
{
unsigned long maxindex = 2147483647ul+2ul;
char* p = new char[maxindex];
for(int i = 0; i < maxindex; i++)
{
p[i] = 65;
}
cout<<"Value at index "<<maxindex-1<<" is "<<p[maxindex-1]<<endl;
delete[] p;
return 0;
}
我在具有 4GB 内存的 64 位 Windows 上运行此程序。当我开始运行时程序内存为 0.99GB,内存使用量上升到 3.07GB 然后程序停止响应并要求我关闭程序。
如果我将 unsigned long maxindex = 2147483647ul+2ul;
中的 2ul
更改为 1ul
,内存使用量会上升到 2.98GB,程序运行成功。
为什么会这样?只需再分配一个 char 元素即可。
最佳答案
将 for(int i
更改为 for(unsigned long i
。
关于c++ - Windows 无法分配内存并停止程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32415345/