Reputation: 1
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.
Upvotes: 0
Views: 1455
Reputation: 7256
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.
Upvotes: 0
Reputation: 1575
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.
Upvotes: 1
Reputation: 50943
Statics live in the same place as globals. The space for them is set at compile time and allocated at load time.
Upvotes: 0
Reputation: 490048
Memory for statics is normally allocated basically as the program loads/just before it starts to execute.
Upvotes: 2
Reputation: 66
There is no allocation for b in this case. It is an int, and is added to the stack when the application is loaded.
Upvotes: -3
Reputation: 23217
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.
Upvotes: 8