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
Logically, q
ceases to exist when fun
exits.
Physically (for suitably loose definitions of "physical"), the story is a bit more complicated, and depends on the underlying platform. C does not do garbage collection (not that garbage collection applies in this case). That memory cell (virtual or physical) that q
occupied still exists and contains whatever value was last written to it. Depending on the architecture / operating system / whatever, that cell may still be accessible by your program, but that's not guaranteed:
6.2.4 Storage durations of objects
2 The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
33) The term ‘‘constant address’’ means that two pointers to the object constructed at possibly different times will compare equal. The address may be different during two different executions of the same program.
34) In the case of a volatile object, the last store need not be explicit in the program.
"Undefined behavior" is the C language's way of dealing with problems by not dealing with them. Basically, the implementation is free to handle the situation any way it chooses to, up to ignoring the problem completely and letting the underlying OS kill the program for doing something naughty.
In your specific case, accessing that memory cell after fun
had exited didn't break anything, and it had not yet been overwritten. That behavior is not guaranteed to be repeatable.