Thread: where are static values stored?

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    69

    where are static values stored?

    Given the following code:

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int do_something(char *);
    
    int
    main(int argc, char *argv) {
    
      char *c = malloc(sizeof(char));
      *c = 'c';
    
      do_something(c);
      do_something(NULL);
    
      return 0;
    
    }
    
    int
    do_something(char *value) {
    
      static char *c;
    
      if (value) {
        c = value;
      }
    
      printf("%c\n", *c);
    
      return 0;
    
    }
    Is the address of the variable c inside do_something stored on the heap, stack, or in a different location in memory? How does the program know to reference the same address/value when the function is called a second time?

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Variables local to a scope are normally destroyed at the end of a statement block. The lifetime of the object is also over, meaning that the stack is popped and memory is physically returned to some sort of pool, or the operating system (whatever the case may be.)

    The only real difference a static variable has from a normal variable is that the lifetime of the variable doesn't end with its' scope, it's value still exists somewhere in memory. When you first call a function with a static variable, the initialization will be performed, but performed not again if the function is recalled. Access is also restricted to places where you can give that value a name.

    It's up to compiler implementors to implement this behavior. I suppose a lot of things could work, like copying a static variable off the stack and silently moving it elsewhere when it's scope has ended. But it's most likely kept in the same memory globals are, as this is possible:
    Code:
    #include <stdio.h>
    #include <assert.h>
    void funcio( void );
    
    int * p;
    
    int main ( )
    {
        funcio();
        assert( *p == 42 );
        return 0;
    }
    
    void funcio ( void )
    {
        static int d = 42;
        p = &d;
    }
    [edit] Oh and, also, the name of a static variable is included in the compiler's symbol table when you build. That's how it remembers what the "special" value is, even if you have another variable with different lifetime semantics. [/edit]

    Clearer now?
    Last edited by whiteflags; 03-02-2008 at 10:13 PM.

  3. #3
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by citizen View Post
    Variables local to a scope are normally destroyed at the end of a statement block. The lifetime of the object is also over, meaning that the stack is popped and memory is physically returned to some sort of pool, or the operating system (whatever the case may be.)

    The only real difference a static variable has from a normal variable is that the lifetime of the variable doesn't end with its' scope, it's value still exists somewhere in memory. When you first call a function with a static variable, the initialization will be performed, but performed not again if the function is recalled. Access is also restricted to places where you can give that value a name.

    It's up to compiler implementors to implement this behavior. I suppose a lot of things could work, like copying a static variable off the stack and silently moving it elsewhere when it's scope has ended. But it's most likely kept in the same memory globals are, as this is possible:
    Code:
    #include <stdio.h>
    #include <assert.h>
    void funcio( void );
    
    int * p;
    
    int main ( )
    {
        funcio();
        assert( *p == 42 );
        return 0;
    }
    
    void funcio ( void )
    {
        static int d = 42;
        p = &d;
    }
    [edit] Oh and, also, the name of a static variable is included in the compiler's symbol table when you build. That's how it remembers what the "special" value is, even if you have another variable with different lifetime semantics. [/edit]

    Clearer now?
    Well here is my tuppence worth....firstly in my opinion static variables are 'normal' variables
    it is the other type of variables which are 'abnormal'
    Anyway thats immaterial really, apart from the disavantage 'unstatic variables' have if you
    are trying to debug a program and you want to see what the value of that variable was
    but can't because it no longer exists.

    But back to the point in question, I don't think the variable is question is a variable, I think it
    just tells the compiler that that function returns an integer, thats all, nothing more.
    So.....it would only exist temporilary on the stack when the function had been called and
    was returning it's return value, so it is really a dynamic variable.

    I could be wrong on this, but have I ever been wrong in the past? (don't bother answering that ).

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    But back to the point in question, I don't think the variable is question is a variable, I think it
    just tells the compiler that that function returns an integer, thats all, nothing more. [...] it would only exist temporilary on the stack when the function had been called and
    was returning it's return value, so it is really a dynamic variable.
    I don't want to claim that the compiler wouldn't optimize my snippet in the crude manner that you implied; however my snippet is not "in question." I was demonstrating my answer: That statics are stored in the same place as globals with access restrictions. My snippet was more of a test to see if you could globally poke at the value of something static. Had you not been able to, the assertion should have failed, (like it would for a pointer to a local automatic variable).

    What you later stated is a possibility, but static variables cannot be destroyed at any point in run time (as dynamic ones can). As I stated, statics could be copied around from the function stack like you said. But the lifetime of the static variable is well defined, unlike a dynamic one: as long as from the point of initialization to the termination of your program. There's no need to explicitly manage static memory, and although implementors may opt to do that behind the scenes, I don't think that is the case for many. Personally, I wouldn't do it that way.

    OP: c will live just as I described but it may point to other places in memory that make c invalid.
    Last edited by whiteflags; 03-02-2008 at 11:28 PM.

  5. #5
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by citizen View Post
    I don't want to claim that the compiler wouldn't optimize my snippet in the crude manner that you implied; however my snippet is not "in question." I was demonstrating my answer: That statics are stored in the same place as globals with access restrictions. My snippet was more of a test to see if you could globally poke at the value of something static. Had you not been able to, the assertion should have failed, (like it would for a pointer to a local automatic variable).

    What you later stated is a possibility, but static variables cannot be destroyed at any point in run time (as dynamic ones can). As I stated, statics could be copied around from the function stack like you said. But the lifetime of the static variable is well defined, unlike a dynamic one: as long as from the point of initialization to the termination of your program. There's no need to explicitly manage static memory, and although implementors may opt to do that behind the scenes, I don't think that is the case for many. Personally, I wouldn't do it that way.

    OP: c will live just as I described but it may point to other places in memory that make c invalid.
    Well my point is basically that the question is a false one, he is not declaring a static
    variable in this case, merely informing the compiler that the function returns an integer.

    It's a fairly academic question to me anyway, my use of passing variable back and forth
    between functions is somewhat 'limited' shall we say.

    And in answer to the OP question, when function is called a second time it merely
    retrives the return value of the stack as it did in the first call.

    I mean how could you access this static variable any way?

    Code:
    int somevariable;
    
    somevariable=do_something;
    That is, I am fairly sure going to return an error similar to:-
    "Oi!! you cannot do that, incompatible types, somevariable is an integer and do_something is a pointer to a function.

    You *might* get away with:-

    Code:
    int somevariable;
    
    somevariable=(int)do_something;
    But I can't see it being of any use.

  6. #6
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by esbo View Post
    "Oi!! you cannot do that, incompatible types, somevariable is an integer and do_something is a pointer to a function.
    This is not a way to call a function in C. If you do not know this bit of info about C - why you still trying to answer any question here?

    You just confusing people with such a crap.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  7. #7
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well my point is basically that the question is a false one, he is not declaring a static
    variable in this case, merely informing the compiler that the function returns an integer.

    It's a fairly academic question to me anyway, my use of passing variable back and forth
    between functions is somewhat 'limited' shall we say.
    But the pointer is a static variable, and he doesn't seem to be using functions in any sort of awkward way (admittedly I'm losing track of what you really are saying).

    Just because he is not taking advantage of the fact that the value is alive for the whole program in this particular snippet, doesn't mean that he wouldn't take advantage in a real project. Static variables are like globals, but because they have scope, it can be easier to locate where errors happen. Some statics aren't even constant: some counters could be static (as in, maybe, reference counters in C++).

    I mean how could you access this static variable any way?
    That being the point: you use a static variable while it is in scope; it sits there otherwise. Anything that might happen, such as passing the value of a static variable to another function, is pretty seamless because you are passing by value. It's more to the point that a static variable has it's value preserved.

    The rest of your statements are irrelevant. No one is using the functions we've written in the manner you describe.
    Last edited by whiteflags; 03-03-2008 at 01:56 AM. Reason: further comments!

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by esbo View Post
    Well here is my tuppence worth....firstly in my opinion static variables are 'normal' variables
    it is the other type of variables which are 'abnormal'
    Yes, in your view and not any sane programmer's view.

    Anyway thats immaterial really, apart from the disavantage 'unstatic variables' have if you
    are trying to debug a program and you want to see what the value of that variable was
    but can't because it no longer exists.
    The advantage with non-global variables is that they are destroyed at the end of the function and hence it they cannot interfere with any other code because they exist no longer, unlike global variables whose state can be modified anywhere and can contain bad data.

    But back to the point in question, I don't think the variable is question is a variable, I think it
    just tells the compiler that that function returns an integer, thats all, nothing more.
    So.....it would only exist temporilary on the stack when the function had been called and
    was returning it's return value, so it is really a dynamic variable.
    It is a static variable, whether you like it or not. In release, the compiler might optimize it, but it is still a static variable and nothing else.

    I could be wrong on this, but have I ever been wrong in the past? (don't bother answering that ).
    I'm going to do it anyway.
    You've been wrong and proved wrong countless times, yet you do not listen.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Right, do go back to the original question:
    a static variable has all the same properties as a global variable, EXCEPT it is not visible outside it's current scope.
    This means that a static variable declared within a function is not visible outside that function.
    A static variable declared outside of a function is visible to this file[1] only.

    [C++ has further extensions to the meaning of static, where static means that the member function or member variable is accessible/exists even when there is no object in itself.]

    [1] Technically, "the compile unit", as in the source file given to the compiler, and any files included within that file.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Anyway thats immaterial really, apart from the disavantage 'unstatic variables' have if you
    are trying to debug a program and you want to see what the value of that variable was
    but can't because it no longer exists.
    They're called "auto" variables, after the keyword of the same name. Besides, you can see the value of automatic variables inside different functions if you need to, in the call stack. If you tried to see variables outside the call stack, you wouldn't get very meaningful values.
    Code:
    C>type viewvar.c
    #include <stdio.h>
    
    void func() {
        puts("In func()");
    }
    
    int main() {
        int mainvar = 3;
        func();
        return 0;
    }
    
    C>gdb -q viewvar.exe
    (gdb) break viewvar.c:4
    Breakpoint 1 at 0x401296: file viewvar.c, line 4.
    (gdb) r
    Starting program: viewvar.exe
    
    Breakpoint 1, func () at viewvar.c:4
    4           puts("In func()");
    (gdb) bt
    #0  func () at viewvar.c:4
    #1  0x004012da in main () at viewvar.c:9
    (gdb) frame 1
    #1  0x004012da in main () at viewvar.c:9
    9           func();
    (gdb) l
    4           puts("In func()");
    5       }
    6
    7       int main() {
    8           int mainvar = 3;
    9           func();
    10          return 0;
    11      }
    (gdb) p mainvar
    $1 = 3
    (gdb) c
    Continuing.
    In func()
    
    Program exited normally.
    (gdb) q
    
    C>
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by vart View Post
    This is not a way to call a function in C. If you do not know this bit of info about C - why you still trying to answer any question here?

    You just confusing people with such a crap.
    I never implied it was a way to call a function hence the rest of your post is based up on
    you initial false assumption and thus the 'crap' would appear to be a product of your own
    mind.

  12. #12
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    The usual name used to refer to the region where global and static variables are stored is simply "the data segment." This is an area of memory distinct from both the stack and heap, where variables are loaded directly into memory from the program image.

    "Uninitialized" global and static variables, or those which are initialized explicitly to zero, are often placed into yet a different segment called "BSS" which is not contained in the program image. This region is automatically zeroed by the runtime during program startup.

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by esbo View Post
    Well my point is basically that the question is a false one, he is not declaring a static
    variable in this case, merely informing the compiler that the function returns an integer.
    Quote Originally Posted by esbo View Post
    I never implied it was a way to call a function hence the rest of your post is based up on
    you initial false assumption and thus the 'crap' would appear to be a product of your own
    mind.
    If we ask you another time, will we get another answer?

  14. #14
    Fountain of knowledge.
    Join Date
    May 2006
    Posts
    794
    Quote Originally Posted by tabstop View Post
    If we ask you another time, will we get another answer?
    Well you will get a reply, whether you get and answer depends to a large extent upon
    whether your 'question' is comprehensible which unfortunately it is not on this occasion.
    ( obviously I mean comprehensibe to someone other than yourself).

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It was comprehensible. First you mentioned "function," as in you were calling a function and it returned an int, and then you mentioned you never mentioned you were calling a function. That's what I gather.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do i do this? (static structure inside class)
    By 39ster in forum C++ Programming
    Replies: 4
    Last Post: 11-17-2008, 03:14 AM
  2. static object never inits
    By krappa in forum C++ Programming
    Replies: 10
    Last Post: 10-30-2008, 12:04 PM
  3. Static functions.... why?
    By patricio2626 in forum C++ Programming
    Replies: 4
    Last Post: 04-02-2007, 08:06 PM
  4. Resizing a triangle. Why is my code not working?
    By gozu in forum Windows Programming
    Replies: 2
    Last Post: 01-20-2007, 06:40 PM
  5. program to unpack packed data
    By vsk in forum C Programming
    Replies: 5
    Last Post: 11-14-2002, 09:17 PM