Dereferencing a pointer to variable beyond its lifetime

suggest change
int* foo(int bar)
    int baz = 6;
    baz += bar;
    return &baz; /* (&baz) copied to new memory location outside of foo. */
} /* (1) The lifetime of baz and bar end here as they have automatic storage   
   * duration (local variables), thus the returned pointer is not valid! */

int main (void)
    int* p;

    p = foo(5);  /* (2) this expression's behavior is undefined */
    *p = *p - 6; /* (3) Undefined behaviour here */

    return 0;

Some compilers helpfully point this out. For example, gcc warns with:

warning: function returns address of local variable [-Wreturn-local-addr]

and clang warns with:

warning: address of stack memory associated with local variable 'baz' returned 

for the above code. But compilers may not be able to help in complex code.

  1. Returning reference to variable declared static is defined behaviour, as the variable is not destroyed after leaving current scope.
  2. According to ISO/IEC 9899:2011 6.2.4 §2, “The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime.”
  3. Dereferencing the pointer returned by the function foo is undefined behaviour as the memory it references holds an indeterminate value.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents