在堆上分配最大内存

时间:2014-09-26 02:20:36

标签: c++ heap-memory

我想知道程序如何在为最终分配抛出错误消息之前使用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;
   }
像这样的事情。我对这个问题非常感兴趣,并且长期致力于此。还可以非常理解如何执行此操作的示例算法。 请帮帮我 提前致谢

1 个答案:

答案 0 :(得分:1)

为什么不是这样的?

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;
相关问题