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

标签 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 然后程序停止响应并要求我关闭程序。

如果我将 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/

相关文章:

c++ - 如何连接字符串并传递给 system() 调用?

java - s 在 Java 中占用 3 个字节吗?当: String s = "abc"; Java

c++ - 我在 C++ 程序中的内存泄漏

c++ - 在同一解决方案的其他项目中的正确位置突出显示选定的 C/C++ 文件

c# - 控制电脑风扇速度的开源软件

c++ - 通过 boost :MPI got error 发送一个简单的 boost 图形对象

c++ - 这两个 C++ 语句有什么区别?

.net - PeakWorkingSet64,没有给我正确的结果

c# - .NET 应用程序天生就是内存密集型的吗?

c++ - 是否在不指定大小格式正确的代码的情况下分配动态数组?