Dereferencing a pointer to variable beyond its lifetime

suggest change
int* foo(int bar)
{
    int baz = 6;
    baz += bar;
    return &baz; /* Returns the address of baz; that address is not valid after return. */
} /* (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 
[-Wreturn-stack-address]

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

  1. Returning a pointer to a static variable is defined, because that object is not destroyed when the block ends.
  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:

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



Table Of Contents