问题
In the following code, I return a pointer to a char
array that is created locally inside the function. Therefore When the return value is assigned to y
, it should all be garbage. This seems to hold true when I print %10s
or %100s
. But when I print %1000s
, I get an output that seems to confound me.
#include <stdio.h>
char* get()
{
char x[1000] ;
int i = 0;
for(; i < 999; ++i)
{
x[i] = 'A';
}
x[999] = '\0';
printf("%1000s\n",x);
return x;
}
int main()
{
char* y = get();
printf("Going to print\n");
printf("%1000s\n",y);
}
The output is
Is it a coincidence that the main()
function is accessing the same memory location that was used to create the local function char array or is it something more concrete?
回答1:
See, once you use the return value of get()
, you're facing undefined behaviour.
After that, nothing is guranteed.
In other words, the output of printf("%1000s\n",y);
## statement cannot be justified. It is, what it is. Undefined.
FWIW, once the get()
function has finsihed execution, the stack space allocated for that function is destroyed and available for usage (if required) by any other function. Maybe you're making unauthorized entry into that part of the physical memory, nothing certain, though.
## - or, printf("%10s\n",y);
or printf("%100s\n",y);
, whatever, wherever y
is accessed.
来源:https://stackoverflow.com/questions/30523611/returning-local-variable-from-a-function