Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No sir. That is not valid. You can't return a pointer to a local variable. Once <code>lab()</code> exits <code>k</code> does not exist and dereferencing a pointer to it causes undefined behavior.</p> <p>Think about where <code>k</code> is stored. Automatic variables that you take the address of are stored on the stack. The stack grows when functions are entered and shrinks when they exit. When <code>lab()</code> returns the stack space that was allocated to <code>k</code> is reclaimed and can be reused by the runtime, possibly for other local variables in some other functions.</p> <p>There are a couple of ways to fix this. The easiest is to have the caller provide a location to store the value in rather than having <code>lab()</code> try to find space. This eliminates the problem of <code>k</code> being deallocated when <code>lab()</code> returns.</p> <pre><code>int* lab(int* i) { *i = 9; return i; } int main(void) { int k; cout &lt;&lt; *lab(&amp;k) &lt;&lt; endl; return 0; } </code></pre> <p>Another way is to declare <code>k</code> as <code>static</code>. Static variables are stored in permanent storage somewhere, not on the stack, so their addresses remain valid throughout the lifetime of the program.</p> <pre><code>int* lab() { static int k=9; return &amp;k; } </code></pre> <p>And yet another way is to allocate memory on the heap using <code>new</code>.</p> <pre><code>int* lab() { int* i = new int; *i = 9; return i; } int main(void) { int* i = lab(); cout &lt;&lt; *i &lt;&lt; endl; delete i; return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload