title: Where to properly delete dynamically allocated object in loop in C++
body: <p>Tutorials, searches, and the dim memory of my C++ formal education have left me clueless as to where I should use delete when I'm using a dynamically allocated object pointer in a loop, such as: </p>
  
  <pre><code>// necessary files are included, this code is within main
  T * t;
  t = foo.getNewT();
  while (!t-&gt;isFinalT()) {
  
      // print t stuff
  
      delete t;         // is this where I should delete t?
      t = foo.getNewT();
  }
  
  delete t;
  </code></pre>
  
  <p>This lack of knowledge has become particularly troublesome on a recent class project. On my laptop (Linux Mint, g++ Ubuntu/Linaro 4.7.3-1ubuntu1) the code ran fine without the delete statement and crashed when I added the delete statement. On the school server (Solaris, g++ (GCC) 3.4.5), the code segfaulted after a few iterations without the delete statement, and runs fine when I add the delete statement.</p>
  
  <p>How do I handle this kind of loop properly so that it will run in most environments?</p>
  
  <p><strong>Additional Info</strong>: 
  The error on my laptop occurs when the program reaches the delete request:</p>
  
  <p><code>*** Error in 'program': free(): invalid next size (fast):</code>...</p>
  
  <p>Some of the other code:    </p>
  
  <pre><code>// T.h
  class T {
      int id;
      int num;
      int strVarPos;
      char * strVar;
    public:
      T();
      ~T();
      // + misc. methods
  }
  
  // T.cpp
  T::T() {
      id = 0;
      num = -1;
      strVarPos = 0;
      char * strVar = new char[11];
      strVar[0] = '\0'
  }
  
  T::~T() {
      delete [] strVar;
  }
  
  // Foo.cpp
  T * Foo::getNewT() {
      T * t = new T;
  
      // populate T's fields
  
      return t;
  }
  </code></pre>
  
  <p><strong>Resolution:</strong></p>
  
  <p>Because a simple test with just <code>T * t</code> and the loop worked ok, I ended up reconstructing the project starting from blank and adding one class at a time, to see when the problem would appear. Turns out that I had added additional content into a dynamically allocated array elsewhere in the program without updating the size constant I was using to initialize the array.</p>
  
  <p>Evidently the school server could only handle the resulting memory discrepancy without crashing if I was making sure to delete the pointers properly (the program didn't run long enough to cause a significant memory leak in my tests), while my laptop wouldn't notice the memory discrepancy until I attempted to call delete (and then would crash).</p>