I had the following code, however I don’t understand what and why it outputs what it does.
int main(){
int *i;
int *fun();
i=fun();
printf("%d\n",*i);
printf("%d\n",*i);
}
int *fun(){
int k=12;
return(&k);
}
The output is 12 and a garbage value. Can somebody explain the output?
Shouldn’t it return garbage values both times?
I know that k is local to fun(), so it would be stored on a stack and that it would be destroyed when fun() goes out of scope. What concept am I missing here?
After the return of
fun,kdoes not exist anymore, so printing the value, stored in the address ofkis undefined behaviour.That’s why you have different/garbage value.
You’re not missing anything, except the fact, that the stack isn’t immediately “annulled”, or something like this. In other words, after the return of
fun, the compiler’s free to do whatever it wants with this memory.