title: Heap corruption detected after normal block
body: <p>I have the following code and am not sure why am I getting the heap corruption detected error when it hits the destructor of Myclass. I believe I am deallocating the memory properly ??</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  using namespace std;
  
  class MyClass{
  private:
      char* mp_str;
  public:
      MyClass():mp_str(NULL){}
      ~MyClass(){
          delete [] mp_str;
      }
  
      void setString(const char* str);
      void printString();
  };
  
  int main(){
      MyClass* a = new MyClass();
      std::vector&lt;MyClass&gt; myVector;
  
      myVector.push_back(*a);
  
      a-&gt;setString("Hello World");
      myVector[0].setString("Goodbye world");
  
      a-&gt;printString();
      myVector[0].printString();
  
      return 1;
  }
  
  void MyClass::setString(const char* const str){
      if(!str)
          return;
  
      size_t len = strlen(str);
  
      if(!this-&gt;mp_str){
          this-&gt;mp_str = new char[len];
          memset(mp_str, 0, len+1);
      }
      strncpy(mp_str, str, len);
  }
  
  void MyClass::printString(){
      if(this-&gt;mp_str)
          cout &lt;&lt; mp_str;
      else
          cout &lt;&lt; "No string found";
  }
  </code></pre>
  
  <p><strong>EDIT</strong>: (Fixed code)</p>
  
  <pre><code>void MyClass::setString(const char* const str){
      if(!str)
          return;
  
      size_t len = strlen(str);
  
      if(!this-&gt;mp_str){
          this-&gt;mp_str = new char[len+1];
          memset(mp_str, 0, len+1);
      }
      strncpy(mp_str, str, len);
  }
  </code></pre>
  
  <p>in main(), I also added</p>
  
  <pre><code>delete a;
  </code></pre>
  
  <p>before calling return 1;</p>