title: Functions that return const char*
body: <p>Although the following code does work, I do not know why. Please explain me.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  const char *f()
  {
      const char *p = "Hello!\n";
  
      return p;
  }
  
  int main()
  {
      cout &lt;&lt; f() &lt;&lt; endl;
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>From what I learnt, the 7 chars in f() are allocated on the stack (?), meaning that their memory will be released as soon as f() ends, however, the pointer returned by f() still points to a valid address in the application memory (meaning "Hello!" is successfully sent to the output). Why?</p>
  
  <p>Same thing goes for</p>
  
  <pre><code>const int *f()
  {
      int i = 5;
      const int *p = &amp;i;
  
      return p;
  }
  
  int main()
  {
      cout &lt;&lt; *f() &lt;&lt; endl;
      system("pause");
      return 0;
  }
  </code></pre>
  
  <p>Can anyone shed some light on this?</p>