0

When is the garbage colletor called in c...Like in the following code

int main()
    {
    int *i;
    int *fun();
    i=fun();
    printf("%d\n",*i);
    printf("%d\n",*i);
    }
    int *fun()
    { 
    int k=12;
    return(&k);
}

the address being returned is of a variable that is no longer available....but printf statement prints 12 first time and garbage value second time...Can anyone explain the reason...

3
Contributors
3
Replies
5
Views
5 Years
Discussion Span
Last Post by manishanibhwani
0

C is not garbage collected. So the garbage collected is never called because there is no garbage collector (unless you're using a lib which provides one - in which case it depends on the lib of course).

The reason that your code (which of course invokes undefined behavior, so might technically behave any way it wants) behaves the way it does is that i contains an address on the stack. The first time you dereference i that address has not yet been re-used because you haven't invoked any other function yet. So it still stores the previous value of k, i.e. 12. The second time you dereference i, printf has been called and presumably stored something on that location on the stack. So it now holds whichever value has been stored there by printf. And that's the value that gets printed.

0

sir I have tried it and I know that by making the variable static printf prints its value all the time...because that variable lifetime has not expired

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.