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?