title: C++ - Valgrind: Invalid write of size 1
body: <p>I have an AVL tree with string keys, and my own String class. In order to fix another issue, I had to add a copy constructor to String. However, valgrind reports an error with it. Here's the constructor:</p>
  
  <pre><code>String::String(const String&amp; s){
      try {
          mStr = new char[1];
      }
      catch (const bad_alloc&amp; e){
          printf("ERROR: No memory\n");
          exit(0);
      }
      mStr[0]='\0';
      mCopy(s);
  }
  
  void String::mCopy(const String&amp; s){
      //  delete[] mStr;
      size_t n = s.Length();
      try{
          mStr = new char[n + 1];
      }
      catch (const bad_alloc&amp; e){
          printf("ERROR: No memory\n");
          exit(0);
      }
      strcpy(mStr, s.mStr);
      mStr[n + 1] = '\0';
  }
  </code></pre>
  
  <p>And here's a part of Valgrind output after adding a string key to my AVL tree:</p>
  
  <pre><code>==7005== Invalid write of size 1
  ==7005==    at 0x4013A1: String::mCopy(String const&amp;) (in /home/ezrafell/Desktop/DA2final/DA3.o)
  ==7005==    by 0x401213: String::String(String const&amp;) (in /home/ezrafell/Desktop/DA2final/DA3.o)
  ==7005==    by 0x40182D: main (in /home/ezrafell/Desktop/DA2final/DA3.o)
  ==7005==  Address 0x5ad450d is 0 bytes after a block of size 61 alloc'd
  ==7005==    at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==7005==    by 0x40136B: String::mCopy(String const&amp;) (in /home/ezrafell/Desktop/DA2final/DA3.o)
  ==7005==    by 0x401213: String::String(String const&amp;) (in /home/ezrafell/Desktop/DA2final/DA3.o)
  ==7005==    by 0x40182D: main (in /home/ezrafell/Desktop/DA2final/DA3.o)
  </code></pre>
  
  <p>Other errors reported by Valgrind also trace back to <code>operator new[]</code> in <code>String::String(String const&amp;)</code>. But what's wrong with it? And how do I rewrite the constructor to avoid this error?</p>