title: Memory management in C++: Creating objects in a loop without crashing the program
body: <p>Consider the following scenario, where I force a <code>std::bad_alloc</code> exception by instantiating the same object multiple times until the program runs out of memory (with these values, the loop cycles around 5019 times before terminating on my machine):</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  
  class myhash{
      int* table;
  
      public:
  
      myhash(int size){
          table = new int[size];
      }
  
  };
  
  
  
  int main(){
      for (int i=0; i&lt;100000; i++){
          cout&lt;&lt;i&lt;&lt;endl;
          myhash* H = new myhash(100000);
      }
  }
  </code></pre>
  
  <p>How can I do something like this, while preventing the program from terminating? I imagined that, using <code>delete</code>, the memory allocated by each object would be freed before instantiating the next, making it possible to run this loop for as long as I'd want. However, after changing the loop to:</p>
  
  <pre><code>for (int i=0; i&lt;100000; i++){
      cout&lt;&lt;i&lt;&lt;endl;
      myhash* H = new myhash(100000);
      delete H;
  }
  </code></pre>
  
  <p>the program still crashes, and aparently it has no effect at all on the number of cycles it runs through before crashing. What's the reason of this, and what would be the correct way of approaching this problem?</p>