title: stringstream, string, and char* conversion confusion
body: <p>My question can be boiled down to, where does the string returned from <code>stringstream.str().c_str()</code> live in memory, and why can't it be assigned to a <code>const char*</code>?</p>
  
  <p>This code example will explain it better than I can</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main()
  {
      stringstream ss("this is a string\n");
  
      string str(ss.str());
  
      const char* cstr1 = str.c_str();
  
      const char* cstr2 = ss.str().c_str();
  
      cout &lt;&lt; cstr1   // Prints correctly
          &lt;&lt; cstr2;   // ERROR, prints out garbage
  
      system("PAUSE");
  
      return 0;
  }
  </code></pre>
  
  <p>The assumption that <code>stringstream.str().c_str()</code> could be assigned to a <code>const char*</code> led to a bug that took me a while to track down.</p>
  
  <p>For bonus points, can anyone explain why replacing the <code>cout</code> statement with</p>
  
  <pre><code>cout &lt;&lt; cstr            // Prints correctly
      &lt;&lt; ss.str().c_str() // Prints correctly
      &lt;&lt; cstr2;           // Prints correctly (???)
  </code></pre>
  
  <p>prints the strings correctly?</p>
  
  <p>I'm compiling in Visual Studio 2008.</p>