title: How to fix 'address of stack memory associated with local variable' when returning a variable address from function?
body: <p>My prof. had me copy and paste the code below she wrote and it kept on giving me bugs. </p>
  
  <p>By running her program, the output was 1 for any value. </p>
  
  <p>Logically, I understand how the function should return the address and in the main it prints the value of it. Theoretically, that is.</p>
  
  <p>So here's what I tried so far:</p>
  
  <p>1) Simply removing the statement p = cube(&amp;n) and replacing with:</p>
  
  <pre><code>    std::cout &lt;&lt; "Cube of " &lt;&lt; n &lt;&lt; " is " &lt;&lt; cube(&amp;n) &lt;&lt; std::endl;
  </code></pre>
  
  <p>This worked.</p>
  
  <p>2) In order to solve the "local variable" error, I made 'result' a global variable.</p>
  
  <p>3) In cube(), i did:</p>
  
  <pre><code>int *cube(int *number)
  {
      int result = (*number) * (*number) * (*number);
      int *newResult = &amp;newResult;
      return newResult;
  }
  </code></pre>
  
  <p>...but it outputted 1 for any integer.</p>
  
  <p>This is the code sample she shared.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int *cube(int *);
  
  int main()
  {
      int n, *p;
      std::cout &lt;&lt; "Enter an int: ";
      std::cin &gt;&gt; n;
  
      p = cube(&amp;n);
  
      std::cout &lt;&lt; "Cube of " &lt;&lt; n &lt;&lt; " is " &lt;&lt; *p &lt;&lt; std::endl;
  
      return 0;
  }
  
  int *cube(int *number)
  {
      int result = (*number) * (*number) * (*number);
      return &amp;result;
  }
  </code></pre>
  
  <p>According to her, the output of this program should be the cube of the inputted integer. For example, 3 in -> 27 out.</p>
  
  <p>Thanks in advance!</p>