title: Deleting array - heap corruption detected
body: <p>I have this simple code (for making things shorted, the important bits are probably only the constructor and the add method.) (Code updated).</p>
  
  <pre><code>#include "general.h"
  template &lt;class T&gt;
  class Template
  {
  private:
      T* oldArr;
      T* newArr;
      int oldArrTop;
      int oldArrLen;
  public:
      Template();
      ~Template();
      void add(const T&amp; val);
      void print();
  };
  
  template &lt;class T&gt;
  Template&lt;T&gt;::Template()
  {
      oldArr=new T[2];
      oldArrTop=0;
      oldArrLen=2;
      newArr=new T[4];
      //newArr's length is always 2.
  }
  
  template &lt;class T&gt;
  Template&lt;T&gt;::~Template()
  {
      delete[] oldArr;
      delete[] newArr;
  }
  
  template &lt;class T&gt;
  void Template&lt;T&gt;::add(const T&amp; val)
  {
      //add normally
      oldArr[oldArrTop]=val;
      //need to copy 2 elements
      if( oldArrTop%2==1 )
      {
          newArr[oldArrTop]=oldArr[oldArrTop];
          newArr[oldArrTop-1]=oldArr[oldArrTop-1];
      }
      oldArrTop++;
      //need to double array's size
      if( oldArrTop==oldArrLen )
      {
          delete[] oldArr;
          oldArr=newArr;
          oldArrLen*=2;
          newArr=new T[oldArrLen*2];
      }
  }
  
  template &lt;class T&gt;
  void Template&lt;T&gt;::print()
  {
      for (int i=0; i&lt;oldArrTop; i++)
          cout&lt;&lt;oldArr[i]&lt;&lt;endl;
  }
  </code></pre>
  
  <p>Here's the code that uses the template:</p>
  
  <pre><code>Template&lt;int&gt; a=Template&lt;int&gt;();
      for(int i=0;i&lt;10;i++)
          a.add(i);
      a.print();
  </code></pre>
  
  <p>However, when I used the template with integers (for example), the first time I delete an array (the first time I get into the "need to doube array's size" part in add, I get a heap corruption error. Anyone knows what the problem is?
  Thank you very much!</p>
  
  <hr>
  
  <p>I'm not sure what fixed it, but the heap corruption error is gone. But, instead of printing the numbers from 0 to 9, it just prints a weird number (-842105421). Any ideas why?</p>