问题
What happens when a pointer to a local variable is returned by a function?
for example
int* foo()
{
int local;
int* ptr = &local;
return ptr;
}
will compiler issue a warning or will it compile and produce unexpected results??
回答1:
Similar kind of question has already been asked : Stack Overflow, local pointer
There are somethings in C which are left for compiler vendor to implement in the way they like. The behaviour of such things are not defined by the creators. Compiler vendors can implement such things as in the way they feel easy and faster. This falls in the same category. The behaviour is undefined and depends on the compiler you are using.
One more such thing is use of more than one pre-increment (pre-decrement) and/or post-increment (post-decrement). When the same code runs on different compilers, you'll may get different output.
回答2:
What happens when a pointer to a local variable is returned by a function?
Undefined behaviour. Anything can happen. The compiler will give you a warning.
This is g++
warning for that mistake:
g++ -Wall -std=c++11 -O3 test.cpp -o test
warning: function returns address of local variable [-Wreturn-local-addr]
来源:https://stackoverflow.com/questions/40991246/returning-pointer-to-a-local-variable