Why is returning a stack allocated pointer variable in a function allowed in C?

They will both be undefined behaviour, if the returned value is accessed. So, none of them are "OK".

You're trying to return a pointer to a block-scoped variable which is of auto storage duration. So, once the scope ends, the lifetime of the variable comes to an end.

Quoting C11, chapter §6.2.4/P2, regarding the lifetime (emphasis mine)

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined [...]

Then, from P5,

An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, [...]

and

For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. [...]

So, in your case, the variable arr is having automatic storage and it's lifetime is limited to the function body. Once the address is returned to caller, attempt to access the memory at that address would be UB.

Oh, and there's no "stack" or "heap" in C standard, All we have is the lifetime of a variable.


Both test and test2() are equivalent. They return an implementation-defined pointer that you must not dereference, or else UB ensues.

If you don't dereference the returned pointer, calling test() or test2() does not result in undefined behavior, but such a function is probably not very useful.