Thread: Memory allocated to variables of a function on different function calls

  1. #1
    Registered User capt.jack's Avatar
    Join Date
    Jun 2010
    Posts
    13

    Memory allocated to variables of a function on different function calls

    Hello World !!
    Today I was reading a topic on 'Local Variables' from 'Thinking in C++ by Bruce Eckel', there Bruce has mentioned that "variables defined local to a function disappear at the end of the function scope. When you call a function again, storage for the variables is created anew and the values are reinitialized."

    Now from this I inferred:

    Inference 1. variables local to a scope get destroyed as soon as their scope ends.
    Say, when we call a function again and again, all its variables are allocated new memory locations and as soon as the function execution gets over all the memory locations are set free.

    And I wrote the following code to seal my inference
    Code:
    #include<iostream>using namespace std;
    
    
    void func()
    {
        int i;
        cout<<"Address of i in func(): "<<(long)&i<<endl;
    }
    
    
    int main()
    {
        int i;
        cout<<"The Address of i in main(): "<<(long)&i<<endl;
        for(int i=0;i<3;i++)
        {
            func();
        }
        cout<<"The Address of i in main() again: "<<(long)&i<<endl;
        func();
    
    
        return 0;
    }
    The results were as follows:
    Code:
    The Address of i in main(): 2293512
    Address of i in func(): 2293468
    Address of i in func(): 2293468
    Address of i in func(): 2293468
    The Address of i in main() again: 2293512
    Address of i in func(): 2293468
    According to Inference 1, on every func() call, 'int i' inside it should have been allocated different memory location, whereas here I see that on every func() call the memory location allocated to 'int i' is same

    from the results of the above code I am forced to infer this:

    Inference 2: for every func() call, the variables disappear at the end of the func() execution and the memory is set free but this freed memory still resides in the big memory chunk allocated to the program at the beginning of its execution, so at the beginning of every func() call the compiler does allocate anew memory location to 'int i' but every time it allocates the memory it lays its hands on the readily available memory locations which turn out to be the same in all the func() calls.
    this may explain the same memory address for 'int i' on every call

    so my question is: which of the two inferences is true or are they both a big fat fallacy ?
    friends, please help me out, I am just a humble beginner of C++

  2. #2
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    When you call a function again, storage for the variables is created anew and the values are reinitialized
    Variables created anew may not mean they 'must' have a different memory location.
    Here they have, but if you, for example put a call to func() inside another function, you may see a different address.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    This is about memory segmentation. Inference 2 is sort of correct, as is manasij7479.

    When a function gets called, its data is placed in the (call) stack segment. When it exits, it is removed. This means if you call a function that calls a function that calls a function you will have a number of stack frames, one for each active function call.

    So if you call a function sequentially from somewhere, its data will end up in the same place each time, as you surmise. But if you call it (eg) recursively, each call has its own frame in a new location. Try this:

    Code:
    #include <stdio.h>
    
    void eg (int r) {
            if (!r) return;
            fprintf(stderr,"%d %p\n", r, &r);
            eg(r-1);
    }
    
    int main() {
            eg(3);
            eg(1);
            eg(1);
            eg(1);
            return 0;
    }
    Notice in the first three the address of r is different whereas in the last three it is always the same.

    Worth noting that this is not a product of any C or C++ standard, and so is not guaranteed. It's determined by the operating system and compiler, which can organize memory in any way what so ever (but mostly as described).
    Last edited by MK27; 09-05-2011 at 02:54 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    You may find some value in:
    Understanding the Stack
    Call Stack wiki

    As a side note, there is no need to "infer" in computer science. This isn't cosmology or quantum mechanics where you are observing unknown behavior and then having to figure out why you observed it. Computer language implementation is a well documented field as well as OS design.
    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
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    there is no need to "infer" in computer science
    Reverse Engineering FTW .

  6. #6
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by manasij7479 View Post
    Reverse Engineering FTW .
    This board always makes me chuckle.
    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.

  7. #7
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by AndrewHunter View Post
    As a side note, there is no need to "infer" in computer science.
    Very strongly disagree. Ideally speaking, you might have a point about how it might be nice if it were really so. But in reality, this is totally ridiculous.

    Also, inferring is a useful skill worth developing. Sort of like poker might be, YMMV

    This isn't cosmology or quantum mechanics where you are observing unknown behavior
    I did not invent atomic physics, the universe, microprocessors, assembly instructions, the C standard, or my operating system, so I'm afraid these all provide me with ample opportunity to observe "unknown behavior".

    Computer language implementation is a well documented field as well as OS design.
    And the people who produce much of that "documentation", whatever their skills at programming and engineering, are often totally pathetic at the task, and produce material that no doubt makes sense to the person who wrote it because they understand said material already, but fails to explain anything to anyone else.

    In fact, I believe it is the norm in programming to code first, answer questions later. Meaning the docs easily lag behind the implementation -- if they even exist.

    I think the OP is completely right to read some and theorize some if what you are recommending is that instead s/he should "just read EVERYTHING first", which no single individual could possible have time to do in a normal lifetime, and would probably not get them far anyway without some good old fashioned conjecture and experiment (and BTW, without that you do not have a "science").

    Trust no one 100%, and instead prove things for yourself.
    Last edited by MK27; 09-05-2011 at 04:45 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Ok, before we get way off track here, let's revisit my side comment. No offense was intended to the OP, and after providing useful links to answering his question, I was simply attempting to state that these resources are out there to learn from. I do strongly agree with experimenting and learning from those experiences in programming.

    My comment was more or less just a statement about the word he used and the connotation that comes with it. As you have stated you did not write the C++ language or the OS you are using, however there is a C++ standard that defines what the language will and will not do, and an associated OS documentation that clearly lays out what it will and will not do and how it will do it.

    I do not have a problem with the OP's question, I was simply pointing out that once you observe some pattern from your programs that you should strive to figure out why, by using the documentation available of which there is plenty. This is what we tell people all the time here.
    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.

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    "variables defined local to a function disappear at the end of the function scope. When you call a function again, storage for the variables is created anew and the values are reinitialized."
    What you haven't realised is that this is not a statement about defining the exact actual inner workings of a compiled program. This is a statement about the concepts and guarantees (or lack thereof) in what you should rely on to be true with regards to the programming language itself.

    Nothing in the quoted text actually amounts to testable behaviour, so writing any program to test the statement, is wrong before you've started. It is like testing a "No Trespassing" sign by attempting to trespass, succeeding in doing so, and then claiming that the sign is wrong. Of course you might have been instantly electrocuted the moment you tried to trespass, but as fate would have it, you weren't. In reality it simply means that you missed the point.

    You shouldn't be trying to infer specific behaviour from the statement made. That's not to say inferring in general is wrong, but it's pretty much wrong in this case.

    I could easily write a basic program for you that does happen to show a variable inside a function having a different address from a different call. A recursive function would be one such easy example. But I wont, because it isn't a point that needs proving.
    Last edited by iMalc; 09-06-2011 at 01:12 AM.
    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"

  10. #10
    Registered User capt.jack's Avatar
    Join Date
    Jun 2010
    Posts
    13
    Quote Originally Posted by MK27 View Post
    This is about memory segmentation. Inference 2 is sort of correct, as is manasij7479. When a function gets called, its data is placed in the (call) stack segment.....
    yeah you're right, I think the "inferred" conclusion can be as follows:

    if a function is called sequentially from somewhere in the program then all its data will end up in the same memory locations. But if we call a function from inside of another function(eg. recursively), then each call will have its own frame in a new memory location

    Quote Originally Posted by AndrewHunter View Post
    My comment was more or less just a statement about the word he used and the connotation that comes with it.
    "Inference" is essential to, and part of, "being human". we engage in inference every day. we infer it is raining/sunny when we see someone with an open umbrella. we infer people are thirsty if they ask for a glass of water. we infer that evidence in a text is authoritative when it is attributed to a scholar in the field. Similarly we "infer" the functioning of the computer/compiler by observing the behaviour of the program and thats what I did and I'm good at doing

    I do not have a problem with the OP's question, I was simply pointing out that once you observe some pattern from your programs that you should strive to figure out why, by using the documentation available of which there is plenty. This is what we tell people all the time here.
    I strongly disagree with your "authoritative advice" and why is it that before or after experimentation, instead of going for a knowledgeable discussion, one should force himself to drown in the vast ocean of documentations just to find a small piece of useful information
    if this was the way computer scientists wanted us learn C++ then Bjarne, in his books, after every topic would have forced us to go through some link to documentation before proceeding further


    My comment was more or less just a statement about the word he used and the connotation that comes with it. As you have stated you did not write the C++ language or the OS you are using, however there is a C++ standard that defines what the language will and will not do, and an associated OS documentation that clearly lays out what it will and will not do and how it will do it.
    if the world of science(in particular comp sc.) was to follow your advice then there would have been no scope for inferences(or learning), because every discussion in this world would have been ended before even a start by someone like you with a link to some boring-indecipherable piece of text called as "documentation"
    after all "questioning, experimenting and inferring" is the process we call learning

    Quote Originally Posted by MK27 View Post
    Trust no one 100%, and instead prove things for yourself.
    I second you on that
    and thanx a lot for clearly explaining and somewhat backing the "Inference 2"
    Last edited by capt.jack; 09-06-2011 at 06:16 AM.

  11. #11
    Registered User capt.jack's Avatar
    Join Date
    Jun 2010
    Posts
    13
    Quote Originally Posted by iMalc View Post
    Nothing in the quoted text actually amounts to testable behaviour, so writing any program to test the statement, is wrong before you've started. It is like testing a "No Trespassing" sign by attempting to trespass, succeeding in doing so, and then claiming that the sign is wrong. Of course you might have been instantly electrocuted the moment you tried to trespass, but as fate would have it, you weren't. In reality it simply means that you missed the point.....
    I strongly disagree with your "No Trespassing" theory where one should force himself into categorizing down any statement on programming behaviour into either some theoretical "one-should-not-care-to-test" statement or a statement (according to you) having some worthy "testable behavior"; because if I would'nt have tested that statement and initiated a discussion here then I might not have(if not later) learnt the "inferred conclusion" in the post above.
    OR can you please go ahead and kindly define the parameters you use to judge a statement's worth to be tested or not


    I could easily write a basic program for you that does happen to show a variable inside a function having a different address from a different call. A recursive function would be one such easy example. But I wont, because it isn't a point that needs proving.
    Revered Sir,
    proving that might be an utter foolishness and worthless for you but for a humble beginner like me, the learning from the proof is worth its salt

    \\Peace //
    Last edited by capt.jack; 09-06-2011 at 06:16 AM.

  12. #12
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    The point iMalc et al are making is that compiler writers can do as they damn well please, because unworthies such as us (who are writing the code) are not allowed (by the language) to actually inspect what's going on behind the scenes from the behavior of the code itself. [This doesn't mean people don't cheat, sometimes, by writing "illegal" code.] The machine has to behave "as if" the memory was returned and then reallocated, but it doesn't have to actually do that; if you've got the optimizer turned on high enough, and the compiler writer was sufficiently clever, then your code at the beginning could elide the stack building and un-building that happens during a function call and use the same memory for the whole program. You could tell by examining the generated machine code, but not from the behavior of the program (you would just see it as "luck" that the machine chose the same address each time).

    If you make the code more complex, you make it more likely that the program has to behave to specs (i.e. you make optimizations harder to find), and calling more than one function in a recursive manner will almost certainly guarantee different values since you will have to have more than one i running around.

  13. #13
    Registered User capt.jack's Avatar
    Join Date
    Jun 2010
    Posts
    13
    Quote Originally Posted by tabstop View Post
    The point iMalc et al are making is that compiler writers can do as they damn well please, because unworthies such as us (who are writing the code) are not allowed (by the language) to actually inspect what's going on behind the scenes from the behavior of the code itself.....
    You nailed your point
    I think the explanation MK27 gave if viewed from your "optimization" point of view yields a clearer picture.
    Thanx a lot for contributing this invaluable view point


    You could tell by examining the generated machine code, but not from the behavior of the program.
    can you please tell me how can we examine the generated machine code and deduce the findings? or is it asking for more(which I'm daringly fond of)

  14. #14
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    "Generated machine code" might be a little bit of a stretch, but presumably if you knew all the opcodes for the chip, and the binary format, etc, then you could "read" an exe file. I don't know anyone who's ever even tried this, and wouldn't expect anyone to actually do so.

    But you can get some idea by having your compiler stop at generating the assembly code, which has got pretty much all the gory details while still at least pretending to be readable. How you do that depends on your compiler. (You can find some information about assembly language on the net; the last time I looked I didn't find anything extremely up-to-date (because people just aren't writing assembly that much any more), but for programs such as the one you've got it will be good enough.)

  15. #15
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    If you are looking into assembly language then check out: Art of Assembly Language - Hyde. It provides a pretty good tutorial on the subject matter, specifically the HLA or High Level Assembly section.
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 01-15-2011, 01:47 PM
  2. Replies: 2
    Last Post: 06-25-2010, 04:04 AM
  3. template variables in function calls
    By DoMeN in forum C++ Programming
    Replies: 1
    Last Post: 02-11-2008, 06:11 AM
  4. arg...function calls
    By 2fastwrx in forum C++ Programming
    Replies: 8
    Last Post: 09-23-2004, 10:55 PM
  5. function calls
    By Draco in forum C Programming
    Replies: 3
    Last Post: 11-09-2003, 04:28 PM

Tags for this Thread