title: Question related to std::string object and c_str() method in 3 different implementations
body: <p>I saw a strange behavior the other day.
  So I wanted to store lines(present in a vector) in a char array and wanted to use '\n' as delimiter.</p>
  <p>I know c_str() method in string class returns a pointer to a char array ending in '\0'.</p>
  <p>Based on my experience/understanding of  C++.(see greet0 and greet2 functions).
  I assumed it should work but it didn't.</p>
  <p>Can anyone explain the different behavior in three greet functions? What is the the scope of the object mentioned in each of the greet function?
  (also i had a guess that the string object was destroyed in greet1 function but if that would have been the case there should be segmentation fault in cout&lt;&lt;&quot;greet1:&quot;&lt;&lt;w1&lt;&lt;endl; but that does not happen so what exactly is happening in background).</p>
  <pre><code>//The snippet that where i first encountered the issue. 
  const char* concatinated_str(std::vector&lt;std::string&gt; lines, const char *delimiter)
  {
          std::stringstream buf;
          std::copy(lines.begin(), lines.end(), std::ostream_iterator&lt;std::string&gt;(buf, delimiter));
          string w = buf.str();
          const char *ret = w.c_str();
  
          return ret;
  
  }
  </code></pre>
  <pre><code>//Implementation 0
  string greet0(){
      string msg = &quot;hello&quot;;
      return msg;
  }
  
  //Implementation 1
  const char* greet1(){
      string msg = &quot;hello&quot;;
      cout&lt;&lt;&amp;msg&lt;&lt;endl;
      return msg.c_str();
  }
  
  //Implementation 2
  const char* greet2(){
      const char* msg = &quot;hello&quot;;
      return msg;
  }
  
  
  int main(){
      auto w0 = greet0();
      cout&lt;&lt;&amp;w0&lt;&lt;endl;
      cout&lt;&lt;&quot;greet0:&quot;&lt;&lt;w0&lt;&lt;endl;
  
      auto w1 = greet1();
      cout&lt;&lt;&quot;greet1:&quot;&lt;&lt;w1&lt;&lt;endl;
      
      const char* w2 = greet2();
      cout&lt;&lt;&quot;greet2:&quot;&lt;&lt;w2&lt;&lt;endl;
  }
  </code></pre>
  <p>Output:</p>
  <pre><code>0x7fff0ff3e8e0
  0x7fff0ff3e8e0
  greet0:hello
  greet1:
  greet2:hello
  </code></pre>