title: How Does Variables Inside Functions Which are Removed From The Stack Behave in Memory
body: <p>i wrote this block of code in C:</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  int* fun() {
      int x = 43;
      int* ret = &amp;x;
      return ret;
  }
  
  int main() {
      int* r = fun();
      printf(&quot;%d&quot;, *r);
      return 0;
  }
  </code></pre>
  <p>the original code was:</p>
  <pre><code>#include &lt;stdio.h&gt;
  
  int* fun() {
      int x = 43;
      return &amp;x;
  }
  
  int main() {
      int* r = fun();
      printf(&quot;%d&quot;, *r);
      return 0;
  }
  </code></pre>
  <p>and i fixed the &quot;Return Local Pointer&quot; Warning by doing</p>
  <pre><code>int* ret = &amp;x;
  </code></pre>
  <p>now my question is that in the first example the code prints 43 and i don't understand why ? shouldn't the pointer be a pointer to garbage value after the function &quot;fun&quot; executes and gets removed from the stack because the variable &quot;x&quot; is destroyed and it no longer holds the value 43 ? so why does dereferencing the pointer &quot;r&quot; after &quot;fun&quot; executes results in 43 ? why does this block of memory that held the variable &quot;x&quot; still not removed even after the function &quot;fun&quot; removed from the stack ?</p>