Thread: Local variables popped from stack or is it ?

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    43

    Local variables popped from stack or is it ?

    Code:
    void main()
    {
      int * j = fun();
    
       printf("%d", *j); 
    }
    
    int * fun()
    {
      int k = 35;
    
       return &k;
    }
    The value 35 is printed in main. However, I expected a garbage value to be printed since k would be popped off the stack once the function fun() returns.

    If I precede the printf statement by some other function call, *j prints out the wrong value implying that the stack contents changed & therefore the wrong value. Does that imply that k remained on stack all this while ?

    Can anyone explain exactly how this is working ?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Perhaps you should examine the assembly output. Note that this is undefined behaviour that you are observing.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    43
    Quote Originally Posted by laserlight View Post
    Perhaps you should examine the assembly output. Note that this is undefined behaviour that you are observing.
    To be honest, I don't know how to do that but I will give it a try...but you do agree then that the output should be garbage ?

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    It is undefined because the memory you are trying to access is no longer reserved by your variable so it could be overwritten. For most languages and I believe C as well (anyone correct me if I am wrong) local variables are stored on the call stack along with other information such as the return address and function paramaters. So from main if you called your fun() your call stack would look like:
    Code:
                                           ________________
                                          |                         
                                          | local  variables    
                                          _________________  
                                          |                         
                                          | return address     
                                           ________________
                                          |                         
                                          | parameters to fun
                                          _________________
    Once your fun() returns control to main this memory is no longer allocated by the call stack to your fun(). Thus in your first example you still recieved the value but only because nothing else happened to need that memory. Now when you called some other function the call stack was again used and, in the case you saw overwrote the memory you were pointing to by j.

    As Laser said this is undefined because depending on the function calls and order you tried to access the memory that specific address may or may not be used again in the call stack.

    A short answer - the variable doesn't exist once the function returns because it goes out of scope and is no longer reserved in the call stack.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    The memory location formerly known as k will continue to exist after the function has returned.

    The exact moment at which that location gets re-used for something else is totally out of your control. All you're seeing at the moment is an element of pure dumb luck.

    Scope is a high level language concept. When something goes out of scope (say a local variable on the return of a function), what disappears is your right to guaranteed access to that variable. The underlying memory used to store that variable almost certainly persists, but it will be re-used again and again.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by trish View Post
    To be honest, I don't know how to do that but I will give it a try...but you do agree then that the output should be garbage ?
    As far as we should be concerned it is garbage. It's garbage that happened to be the value 35 when you examined it.
    It could just as easily have been intentionally overwritten by a compiler that tries to catch users writing code the has undefined behaviour. But generally a value in memory is left as it was until something else uses it, only because it isn't worth spending time overwriting memory with a differnt value when nothing is going to look at it. Had you called any other function in the mean time you'd probably find that the value was different.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by trish View Post
    Code:
    void main()
    {
      int * j = fun();
    
       printf("%d", *j); 
    }
    
    int * fun()
    {
      int k = 35;
    
       return &k;
    }
    The value 35 is printed in main. However, I expected a garbage value to be printed since k would be popped off the stack once the function fun() returns.

    If I precede the printf statement by some other function call, *j prints out the wrong value implying that the stack contents changed & therefore the wrong value. Does that imply that k remained on stack all this while ?

    Can anyone explain exactly how this is working ?
    Dumb luck... because nothing else has overwritten that stack location yet.

    Popping a variable does not reset it to 0... it merely abandons that slot on the stack.
    The same is true with free() ... it doesn't reset memory, it merely abandons it.

    In a more complex program it would fail.

  8. #8
    Registered User
    Join Date
    Jan 2010
    Location
    Ca, US
    Posts
    29
    See what happens when you print *j a second time right after the first. There is a good chance the first call to printf will use that memory space and the second printf will print "garbage".
    So even if it still holds your old data in that printf, good chance even in the next call it will be gone.

    Dylan

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 12-02-2009, 08:47 AM
  2. local stack variables
    By Amyaayaa in forum C++ Programming
    Replies: 25
    Last Post: 10-07-2008, 01:13 PM
  3. local and global variables???
    By geo_c in forum C Programming
    Replies: 5
    Last Post: 08-23-2004, 03:02 PM
  4. local variables
    By Gil22 in forum C++ Programming
    Replies: 14
    Last Post: 04-09-2003, 09:13 PM
  5. local variables
    By Unregistered in forum C Programming
    Replies: 14
    Last Post: 03-20-2002, 02:55 PM