开发者

When are static function variables allocated?

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 i开发者_JAVA百科nt 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.


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.


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


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.


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


When static is used inside a function block, the keyword static changes the storage class of the variable or function, which means static int b; is saying that b is a static variable rather than an automatic one.

When talking about storage class, static one is initialized in static memory before the program runs, and is there all the time when the program runs, while automatic one is initialized in run-time stack or heap when reaches certain block and is destroyed when the program goes out of the block.


When static is used outside as in the static int a; shows, this is rather another case. It changes the linkage of the variable to be internal while the default value is external. And it has nothing to do with the storage class of the variable or function.

With static, a is internal, which means it is only accessible to those within this file. Without static, a is set to be external by default, which means it is accessible to those within and out of the file where a is defined.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜