C Language Undefined behavior Dereferencing a pointer to variable beyond its lifetime


Example

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 
[-Wreturn-stack-address]

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.