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.
static
is defined behaviour, as the variable is not destroyed after leaving current scope.foo
is undefined behaviour as the memory it references holds an indeterminate value.