title: Invalid object access c++
body: <p>I was trying to run this code from the Stroustroup's C++ book, there is some code which I added as everything was not available in the book. I keep hitting the following problem. I know there are multiple questions here on the same error, but my code is different and hence this question.</p>
  
  <p>The error is </p>
  
  <blockquote>
    <p>copy(5826,0x7fff76b09300) malloc: <strong>* error for object 0x7ff6a9404c18: incorrect checksum for freed object - object was probably modified after being freed.
    *</strong> set a breakpoint in malloc_error_break to debug
    Abort trap: 6</p>
  </blockquote>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;iostream&gt;
  
  using namespace std;
  class Vector {
  private:
      double * elem; // elem points to an array of sz doubles
      int sz;
  public:
      Vector(int s) {
          sz = s;
          elem = new double[sz];
          for (int i = 0; i&lt;sz; i++) {
              elem[i] = i;
          }
      }
      ~Vector() { delete[] elem; } // destructor: release resources
      Vector(const Vector&amp; a); // copy constructor
      Vector&amp; operator=(const Vector&amp; a); // copy assignment
      double&amp; operator[](int i);
      const double&amp; operator[](int i) const;
      int size() const;
  };
  
  
  Vector::Vector(const Vector&amp; a) // copy constr uctor
  {
      elem = new double[sz], // allocate space for elements
          sz = a.sz;
      for (int i = 0; i != sz; ++i) // copy elements
          elem[i] = a.elem[i];
  }
  
  
  double&amp; Vector::operator[](int k) {
      return this-&gt;elem[k];
  }
  
  
  Vector&amp; Vector::operator=(const Vector&amp; a) // copy assignment
  {
      double* p = new double[a.sz];
      for (int i = 0; i != a.sz; ++i)
          p[i] = a.elem[i];
      delete[] elem; // delete old elements
      elem = p;
      sz = a.sz;
      return *this;
  }
  
  
  int main() {
      Vector v1(10);
      Vector v2 = v1;
      v1[0] = 2;
      v2[1] = 3;
      cout &lt;&lt; v1[0] &lt;&lt; "\n";
      return 0;
  }
  </code></pre>