title: Why access c_str returned from object on the heap get garbage value?
body: <p>Sometimes I need to call C++ objects from C. After some search, I know I can use <code>extern &quot;C&quot;</code> to wrap some interfaces which can be called from C. Here is my code:</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  
  class Dog
  {
  public:
      Dog(std::string nm = &quot;Eddie&quot;): name(nm), sound(&quot;woof&quot;)
      {
          std::cout &lt;&lt; &quot;Dog &quot; &lt;&lt; name &lt;&lt; &quot; is coming.&quot; &lt;&lt; std::endl;
      }
      ~Dog()
      {
          std::cout &lt;&lt; &quot;Dog &quot; &lt;&lt; name &lt;&lt; &quot; ran way.&quot; &lt;&lt; std::endl;
      }
      std::string bark()
      {
          return sound;
      }
  private:
      std::string name;
      std::string sound;
  };
  
  extern &quot;C&quot; {
      void * dog_come();
      void   dog_delete(void *);
      const char * dog_bark(void *);
  }
  
  void * dog_come()
  {
      return new Dog();
  }
  
  void dog_go(void *pd)
  {
      delete (Dog *)pd;
  }
  
  const char * dog_bark(void *pd)
  {
      Dog *pdog = (Dog *)pd;
      return pdog-&gt;bark().c_str();
  }
  
  int main(int argc, char *argv[])
  {
      Dog hobo(&quot;Hobo&quot;);
      std::cout &lt;&lt; hobo.bark() &lt;&lt; std::endl;
  
      void *eddie = dog_come();
      std::cout &lt;&lt; dog_bark(eddie) &lt;&lt; std::endl;
      dog_go(eddie);
  
      return 0;
  }
  
  </code></pre>
  <p>After execute the following command:</p>
  <pre><code>g++ -std=c++11 main.cpp
  ./a.out
  </code></pre>
  <p>I think the output should be:</p>
  <pre><code>Dog Hobo is coming.
  woof
  Dog Eddie is coming.
  woof
  Dog Eddie ran way.
  Dog Hobo ran way.
  </code></pre>
  <p>However, the real output I got is:</p>
  <pre><code>Dog Hobo  is coming.
  woof
  Dog Eddie  is coming.
  $%^&amp; /**&lt; garbage here */
  Dog Eddie ran way.
  Dog Hobo ran way.
  </code></pre>
  <p>Can someone tell me why?</p>