Automatic vs. Static Duration

This is a discussion on Automatic vs. Static Duration within the C++ Programming forums, part of the General Programming Boards category; I come from a background in Pascal, where there is no "automatic duration", unless you want to count function data ...

  1. #1
    JMB
    JMB is offline
    Registered User
    Join Date
    Oct 2002
    Posts
    10

    Automatic vs. Static Duration

    I come from a background in Pascal, where there is no "automatic duration", unless you want to count function data variables that are pushed onto the stack when the function is called. Static duration would mean that global variables, like in an asm program, are thrown in a part of the actual .exe, whether initialized or not.

    I'm confused about the meaning of automatic duration in C++. Are the variables actually allocated at runtime? Would that be on the heap or on the stack? I understand that global variables are static the entire program, so I assume they are defined at compile time. I also understand that within any block, variables are either dynamic or automatic duration; meaning that main() itself uses variables that are auto. Does this mean that if I write:

    char myStr[] = "abcdefghijklmnopqrstuvwxyz";

    in main, or another block, that first space is made on the stack for myStr, and then that string is copied to the stack? As opposed to storing the string at compile-time and pointing myStr to it? Wouldn't this have efficiency draw backs? Or am I misunderstanding the meaning of it?

    Thanks for clarifying!
    Proud to be straightedge.

  2. #2
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    You have spelled out everything correctly.

    The main function generates automatic variables because the variables are contained in a block, just like any other function. These are all copied onto the runtime function stack.

    Global variables are static and created during compile time.

    In addition, I believe that if you define the variable in another file and declare the same variable in a block preceded with the keyword 'extern' than the declaration referes to the file where the variable was defined and it has static storage class but can be used in multiple files.
    Code:
    myfile0.cpp
    int num;
    Code:
    myfile1.cpp
    #include<iostream>
    int main()
    {
      extern int num;  //static storage class
      num += 1;
       ...
       return 0;
    }
    The duration of the static variables is the lifetime of the program, however it doesn't reflect their scope.

  3. #3
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789

    Re: Automatic vs. Static Duration

    Originally posted by JMB
    I come from a background in Pascal, where there is no "automatic duration", unless you want to count function data variables that are pushed onto the stack when the function is called. Static duration would mean that global variables, like in an asm program, are thrown in a part of the actual .exe, whether initialized or not.

    I'm confused about the meaning of automatic duration in C++. Are the variables actually allocated at runtime? Would that be on the heap or on the stack? I understand that global variables are static the entire program, so I assume they are defined at compile time. I also understand that within any block, variables are either dynamic or automatic duration; meaning that main() itself uses variables that are auto. Does this mean that if I write:

    char myStr[] = "abcdefghijklmnopqrstuvwxyz";

    in main, or another block, that first space is made on the stack for myStr, and then that string is copied to the stack? As opposed to storing the string at compile-time and pointing myStr to it? Wouldn't this have efficiency draw backs? Or am I misunderstanding the meaning of it?

    Thanks for clarifying!
    Basically, when you enter a function block, the compiler creates a stack frame to hold space for the variables declared in that block......In C++, an instance of an object is created when the flow of code first encounters its declaration.....so at that point, the relevant constructors are called, and its values are copied to the stack frame........then when the function ends, the stack frame is discarded...so the values still sit there, but the compiler doesnt guarantee they will stay as they were (chances are they will be overwritten rather quickly) and wont let you access them.....therefore these variables are automatic...they exist in the stackframe created by the function, and when the function ends, the stack frame is no more - therefore the variable is finished....

    Interestingly,

    Code:
    char* sz = "Hello";
    and

    Code:
    	char sx[] = "Hello";
    are treaded differently.......With the first, the "Hello" is usually copied to a global section (usually const), and the pointer to it (sz) is copied to the stack....with the second, the charectors are each copied to the stack, and the compiler substitutes sx for a pointer to the first char sat on the stack....So with the first, 4 bytes are copied to the stack (assuming 32bit processor and most common systems) but the data cant be altered, with the second, 5 bytes are copied (again assuming chars are 1 byte) and an extra 1 for the NULL char, but they can be altered.....

  4. #4
    JMB
    JMB is offline
    Registered User
    Join Date
    Oct 2002
    Posts
    10
    Interesting. I wonder why they do it that way?
    Proud to be straightedge.

  5. #5
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    I can't say for sure "why" but I can say for sure that there are ways to use it to your advantage. For instance:

    Code:
    char sz[256] = "C:\\windows\\desktop\\";
    The advantage here may not be apparent at first, however, this gives you an array of 256 chars that already has the name of the windows 9x default desktop directory in it. At this point you can append a filename to the end of the buffer.

    Code:
    strcat(sz, "hello world.c");
    However, this code wouldn't fly:

    Code:
    /*EDIT: fixed a typo on this line*/
    char *sz = "C:\\windows\\desktop\\";
    
    strcat(sz, "hello world.c");
    I do believe that this was the intent of what Fordy explained.

  6. #6
    JMB
    JMB is offline
    Registered User
    Join Date
    Oct 2002
    Posts
    10
    I guess what I'm asking is... Fordy said that in the case of declaring an automatic c-string variable, the bytes are copied to the stack. This makes sense, of course. But what I'm wondering -- is the string "Hello" stored in a global section, somewhere in the program, so that X number of bytes can be copied from that section to the stack. (Which means if more than one variable is assigned "Hello", only one instance needs to be used). Or is the data stored in that block, and copied to the stack the instant it is referenced?

    Ex:

    Code:
    void someFunct1()
    {
        char thisFunct[] = "Hello";
        // ...
    }
    
    void someFunct2()
    {
        char thisFunct2[] = "Hello";
        // ...
    }
    Now, it would seem a waste to me, that these two auto vars generate code that does something like:

    PUSH '\0'
    PUSH 'l'
    PUSH 'l'
    ...

    rather than placing Hello in the data segment (or whatever it is called under win32) and copying that string of bytes to the stack. This way, the original "Hello" won't be modified...

    And an auto int, like

    Code:
    int main()
    {
        int myInt = 255;
    }
    I suppose as an auto variable, that would PUSH the 4 bytes to the stack and reference myInt to it. But why do that? Other compilers would probably stick 255 somewhere in the .exe and point myInt to it, rather than make it allocated dynamically.

    something like

    myInt dw 255

    as opposed to

    PUSH 255
    mov [myInt], SP

    Does that make sense? geez I'm confused. :)

    I could figure this out if I had a hex editor. But I'm worried about the specific standards here. Thanks.

    -JMB
    Proud to be straightedge.

  7. #7
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Ok....firstly, yeah.....if you char thisFunct[] = "Hello"; then a global copy of "Hello" is stored in the exe and when that above code is reached, those chars are copied to the stack frame....

    You can place the string in a global, changable section by declaring "char thisFunct[] = "Hello";" outside of any function body....now every func can modify the chars, but this may be a pain if you dont want to risk every piece of code having access to this data....that's a reason why stack varibles can be prefered in C++ (Also, if you declare a global object you have no control over when the construction of object that object takes place...but that has no relevance here....)

    As to the int well your not really right on how its accessed......the compiler sets aside memory on the stack...it creates a "frame" that exists between the EBP and ESP pointers.....and on this frame, the values of the variables are stored......so when we have say

    //int x;
    x = 5;

    That might dissasemble to

    mov [ebp-8],5

    So all the stack variables are are relative stack frame positions....

    does that make sense? Best bet is to get a decent debugger and follow the code through step by step....after the first bit of ASM code in a function....look at the EBP and ESP registers.they show the start and end of the frame......now keep a look at that frame in your memory window as you step through some simple code

  8. #8
    JMB
    JMB is offline
    Registered User
    Join Date
    Oct 2002
    Posts
    10
    That helps! Thanks again everyone. :)

    -JMB
    Proud to be straightedge.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  3. LNK2001 ERROR!!! need help
    By lifeafterdeath in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2008, 05:05 PM
  4. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 04:42 PM
  5. The Timing is incorret
    By Drew in forum C++ Programming
    Replies: 5
    Last Post: 08-28-2003, 04:57 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21