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...

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.

int k=12;

Now try this and you will see different behavior
static int k=12;

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.