title: Possible memory leak using C++ string
body: <p>Consider the following C++ program:</p>
  
  <pre><code>#include &lt;cstdlib&gt; // for exit(3)
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  using namespace std;
  
  void die()
  {
      exit(0);
  }
  
  int main()
  {
      string s("Hello, World!");
      cout &lt;&lt; s &lt;&lt; endl;
      die();
  }
  </code></pre>
  
  <p>Running this through valgrind shows this (some output trimmed for brevity):</p>
  
  <pre><code>==1643== HEAP SUMMARY:
  ==1643==     in use at exit: 26 bytes in 1 blocks
  ==1643==   total heap usage: 1 allocs, 0 frees, 26 bytes allocated
  ==1643==
  ==1643== LEAK SUMMARY:
  ==1643==    definitely lost: 0 bytes in 0 blocks
  ==1643==    indirectly lost: 0 bytes in 0 blocks
  ==1643==      possibly lost: 26 bytes in 1 blocks
  ==1643==    still reachable: 0 bytes in 0 blocks
  ==1643==         suppressed: 0 bytes in 0 blocks
  </code></pre>
  
  <p>As you can see, there's a <strong>possibility</strong> that 26 bytes allocated on the heap were lost.  I know that the <code>std::string</code> class has a 12-byte struct (at least on my 32-bit x86 arch and GNU compiler 4.2.4), and "Hello, World!" with a null terminator has 14 bytes.  If I understand it correctly, the 12-byte structure contains a pointer to the character string, the allocated size, and the reference count (someone correct me if I'm wrong here).</p>
  
  <p>Now my questions:  How are C++ strings stored with regard to the stack/heap? Does a stack object exist for a <code>std::string</code> (or other STL containers) when declared?</p>
  
  <p>P.S. I've read somewhere that valgrind <strong>may</strong> report a false positive of a memory leak in some C++ programs that use STL containers (and "almost-containers" such as <code>std::string</code>).  I'm not too worried about this leak, but it does pique my curiosity regarding STL containers and memory management.</p>