We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,973 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

garbage collector

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
3 Hours
Discussion Span
9 Months Ago
Last Updated
4
Views
manishanibhwani
Light Poster
29 posts since Jan 2010
Reputation Points: 10
Solved Threads: 3
Skill Endorsements: 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.

sepp2k
Posting Whiz in Training
227 posts since Jul 2012
Reputation Points: 62
Solved Threads: 45
Skill Endorsements: 8

int k=12;

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

Ancient Dragon
Achieved Level 70
Team Colleague
32,125 posts since Aug 2005
Reputation Points: 5,836
Solved Threads: 2,575
Skill Endorsements: 69

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

manishanibhwani
Light Poster
29 posts since Jan 2010
Reputation Points: 10
Solved Threads: 3
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0659 seconds using 2.69MB