tags:

views:

104

answers:

5

I have a question in allocation of memory for static variables. Please look at the following snippet.

#include<stdio.h>
#include<conio.h>

void fun();

static int a;

void main()
{
    fun();
    getch();
}

void fun()
{
    static int b;
}

Can someone please explain me when memory will be allocated for static int b in function fun (before main is executed or when the function is located). I knew that memory for static will be allocated only once, but I want to knew when memory will be allocated for it. Please explain.

I am using 64 bit processor, turbo c compiler, windows 7 operating system.

+6  A: 

Memory for static variables is allocated when your program is loaded. Static variables in a function are initialized before the function is called for the first time.

Cogwheel - Matthew Orlando
In this case, since the value isn't specified, I would expect space to be allocated in the program's BSS segment. This is just a block of 0 initialised memory allocated by the loader at runtime.
torak
I would not count on variables without initialization in the code, to be initialized to 0 on allocation.
pascal
@pascal, the standard (§6.7.8/10) requires that static arithmetic variables without an initializer be initialized to 0.
Matthew Flaschen
@Matthew thanks for the info.
pascal
A: 

There is no allocation for b in this case. It is an int, and is added to the stack when the application is loaded.

Daryl
no, not to the stack.
Tom
More like .bss.
Nathon
+2  A: 

Memory for statics is normally allocated basically as the program loads/just before it starts to execute.

Jerry Coffin
A: 

Statics live in the same place as globals. The space for them is set at compile time and allocated at load time.

Nathon
+1  A: 

Memory for static variables (both a and b in the example question) is allocated at compile time. You can verify this by examining your map file. Be aware that, depending on the detail provided in the map file, you may not see the variable name of the static variable, rather simply that the corresponding amount of memory has been allocated. They are initialized when the program is loaded along with the global variables...not the first time the function is called.

semaj