在堆上分配最大内存

allocate maximum memory on heap

本文关键字:大内 内存 分配      更新时间:2023-10-16

我想知道程序如何在抛出错误消息进行最终分配之前使用new[]来分配最大内存量,就像一样

   #include <iostream>
   using namespace std;
   int main()
   {
   try
   {
      do
      {
      int i = new int;
      throw sth;
      .......
      }while(true);
   }
   catch(Exception){
    cerr<<"out of range"<<endl;
   }
    return 0;
   }

像这样的东西。我真的被这个问题打动了,并为此工作了很长时间。如何做到这一点的示例算法也可能非常受欢迎。请帮帮我提前感谢

为什么不做这样的事情?

size_t s = 0;
char* p = nullptr;
while(p = new (std::nothrow) char[++s]) delete[] p;
std::cout << "Max successful heap allocation: " << s - 1 << " bytes." << std::endl;