You can look at it this way. A variable represents a place in memory. Lifetime of a variable is defined by validity of this place in memory. The place in memory keeps a value. Any copy operation just copies values from one place in memory to another.
Every such memory place has an address. A pointer to a variable is just another variable which value is an address of another variable. A copy of a pointer is just a copy of an address from one place to another.
If a variable is declared in the global scope, than its memory will be valid till the exit of the program. If the variable is declared non-statically in a procedure, then its memory is valid till the end of this procedure. Technically it is probably allocated on stack which gets unallocated when the procedure returns, making this memory not valid.
In your case if pointer x
points to a variable from a global scope, the variable itself is valid until the exit from the procedure. However, the return statement copies the value from the x
into a different location just before the latter becomes invalid. As a result the value of x
will end up in bar
. This value is the address of a static variable which is still valid.
There would be a different story if you try to return the address of x
, i.e. &x
. This would be an address of memory which existed inside of the procedure. After return it will point to an invalid memory location.
So, if your something_non-local
points to such a thing, than you are in trouble. It should point to something static or something in heap.
BTW, malloc
allocates a memory in heap which is valid till you use free
.