Windows无法分配内存并停止程序?

时间:2015-09-05 16:33:54

标签: c++ memory new-operator

#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然后程序停止响应,我被要求关闭程序。

如果我将2ul中的unsigned long maxindex = 2147483647ul+2ul;更改为1ul,则内存使用量将增加到2.98GB,程序将成功运行。

为什么会这样?它只需要分配一个char元素。

1 个答案:

答案 0 :(得分:1)

for(int i更改为for(unsigned long i

相关问题