title: The lifetime of a pointer reference in C++
body: <p>I wrote some code that involves moving and changing variables in C++. Below is what I have wrote.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  void six(int*&amp; ptr) {
      int s = 6;
      ptr = &amp;s;
  }
  
  int main() {
      int f = 5;
      int* ptr = &amp;f;
  
      std::cout &lt;&lt; *ptr &lt;&lt; '\n';
      six(ptr);
  
      if (ptr) {
          std::cout &lt;&lt; *ptr;
      }
      else {
          std::cout &lt;&lt; "null\n";
      }
  
      return 0;
  }
  </code></pre>
  
  <p>so this prints:</p>
  
  <pre><code>5
  6
  </code></pre>
  
  <p>I tried another code, adding a single line:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  void six(int*&amp; ptr) {
      int s = 6;
      ptr = &amp;s;
      free(&amp;s); // added line
  }
  
  int main() {
      int f = 5;
      int* ptr = &amp;f;
  
      std::cout &lt;&lt; *ptr &lt;&lt; '\n';
      six(ptr);
  
      if (ptr) {
          std::cout &lt;&lt; *ptr;
      }
      else {
          std::cout &lt;&lt; "null\n";
      }
  
      return 0;
  }
  </code></pre>
  
  <p>Obviously, this gives an error after printing <code>5</code> because what the modified pointer is pointing is not available when called the second time.</p>
  
  <p>However, I am confused at the first case. When calling <code>six</code> in the main function, variable <code>s</code> is not in the main scope, but the value itself still continues to remain in the memory to be referenced. Doesn't C++ automatically destroy variables and clean them when it goes out of the scope? Is this a memory leak?</p>