Returning address of local variable and program still work : <p>Lets say this is the snapshot I want to talk about. In this code, main function calls 'foo' which returns address of locally declared variable 'a'. I was under the impression that locally declared variables de-allocates the memory when they go out of scope. Variable 'a' should be de-allocated after call to foo is done and there should not be anything left related to 'a'. But in this case, it seems to be breaking that basic assumption. What is going on underneath?</p>

<pre><code>int* foo() {
  int a = 5;
  return &amp;a;
}

int main() {
  int* p = foo();
  // Prints 5
  std::cout &lt;&lt; "Coming from foo = " &lt;&lt; *p &lt;&lt; std::endl;
  *p = 8;
  // Prints 8
  std::cout &lt;&lt; "Setting explicitly = " &lt;&lt; *p &lt;&lt; std::endl;
}
</code></pre>
