title: c++ memory error when using malloc/realloc/free on std::string
body: <p>I wrote a small piece of code like this:</p>
  
  <pre><code>template &lt;class T&gt;
  void
  test()
  {
      T* ptr = nullptr;
  
      ptr = (T*)malloc(1 * sizeof(T));
  
      new ((void*)ptr) T(T());
  
      ptr = (T*)realloc(ptr, 2 * sizeof(T));
  
      new ((void*)(ptr + 1)) T(T());
  
      (ptr)-&gt;~T();
      (ptr + 1)-&gt;~T();
  
      free(ptr);
  }
  
  struct foo
  {
      foo() : ptr(malloc(10)) {}
      ~foo() { free(ptr); } 
      void* ptr;
  };
  
  int
  main()
  { 
      test&lt;int&gt;(); // this is ok
      test&lt;foo&gt;(); // this is ok
      test&lt;std::string&gt;(); // memory error :(
  
      return 0;
  }; 
  </code></pre>
  
  <p>When T is [int] or [foo], everything works fine. But using [std::string] as T causes valgrind to report memory errors like this:</p>
  
  <pre><code>==18184== Memcheck, a memory error detector
  ==18184== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
  ==18184== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
  ==18184== Command: ./a.out
  ==18184== 
  ==18184== Invalid free() / delete / delete[] / realloc()
  ==18184==    at 0x4C2C20A: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==18184==    by 0x401074: void test&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;() (tmp.cpp:26)
  ==18184==    by 0x400CFC: main (tmp.cpp:44)
  ==18184==  Address 0x5a89e70 is 16 bytes inside a block of size 32 free'd
  ==18184==    at 0x4C2CC37: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==18184==    by 0x401042: void test&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;() (tmp.cpp:22)
  ==18184==    by 0x400CFC: main (tmp.cpp:44)
  ==18184==  Block was alloc'd at
  ==18184==    at 0x4C2AB8D: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==18184==    by 0x40100F: void test&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;() (tmp.cpp:18)
  ==18184==    by 0x400CFC: main (tmp.cpp:44)
  ==18184== 
  ==18184== 
  ==18184== HEAP SUMMARY:
  ==18184==     in use at exit: 0 bytes in 0 blocks
  ==18184==   total heap usage: 9 allocs, 10 frees, 72,856 bytes allocated
  ==18184== 
  ==18184== All heap blocks were freed -- no leaks are possible
  ==18184== 
  ==18184== For counts of detected and suppressed errors, rerun with: -v
  ==18184== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
  </code></pre>
  
  <p>why only [std::string] leads to memory problem while [foo] also has malloc/free in both ctor &amp; dtor ?</p>
  
  <p>I'm using g++ 6.2.1 and valgrind 3.12.0</p>