I recently read about scope rules in C. It says that a local or auto variable is available only inside the block of the function in which it is declared. Once outside the function it no longer is visible. Also that its lifetime is only till the end of the final closing braces of the function body.
Now here is the problem. What happens when the address of a local variable is returned from the function to the calling function ?
For example :-
main()
{
int *p=fun();
}
int * fun()
{
int localvar=0;
return (&localvar);
}
once the control returns back from the function fun, the variable localvar is no longer alive. So how will main be able to access the contents at this address ?
The address can be returned, but the value stored at the address cannot reliably be read. Indeed, it is not even clear that you can safely assign it, though the chances are that on most machines there wouldn’t be a problem with that.
You can often read the address, but the behaviour is undefined (read ‘bad: to be avoided at all costs!‘). In particular, the address may be used for other variables in other functions, so if you access it after calling other functions, you are definitely unlikely to see the last value stored in the variable by the function that returned the pointer to it.
One reason is often ‘dynamic memory’. The
malloc()family of functions return a pointer to new (non-stack) memory.Another reason is ‘found something at this location in a value passed to me’. Consider
strchr()orstrstr().Another reason is ‘returning pointer to a static object, either hidden in the function or in the file containing the source for the function’. Consider
asctime()et al (and worry about thread-safety).There are probably a few others, but those are probably the most common.
Note that none of these return a pointer to a local (stack-based) variable.