I thought that once a function returns, all the local variables declared within (barring those with static
keyword) are garbage collected. But when I am trying out the following code, it still prints the value after the function has returned. Can anybody explain why?
int *fun();
main() {
int *p;
p = fun();
printf("%d",*p); //shouldn't print 5, for the variable no longer exists at this address
}
int *fun() {
int q;
q = 5;
return(&q);
}
There's no garbage collection in C. Once the scope of a variable cease to exist, accessing it in any means is illegal. What you see is UB(Undefined behaviour).
It's undefined behavior, anything can happen, including appearing to work. The memory probably wasn't overwritten yet, but that doesn't mean you have the right to access it. Yet you did! I hope you're happy! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With