When is a local static variable stored in memory? - c

At what point does the language require the compiler to store a local static variable into memory? Is it at compile time? Or at runtime when the function that contains the local static variable is called?
int* GetMyVariable()
{
static int A = 50;
return &A;
}
I want to be able to only use memory for 'A' if GetMyVariable() is called. If static doesn't work like this, then is a dynamic allocation my only option? Thanks for your time.

When is a local static variable stored in memory
This is done prior to the execution of the program.
(C99, 6.2.4p3) "An object whose identifier is declared with external
or internal linkage, or with the storage-class specifier static
has static storage duration. Its lifetime is the entire execution
of the program and its stored value is initialized only once,
prior to program startup."

A static variable in C exists throughout the whole execution of a program. Therefore, you can safely take the address of that variable at any time.

Related

When are LOCAL static variables initialized

I keep on seeing the same sentence that static variables are initialized only once, and I also saw a sentence stating that "when the block is entered for the first time".
Are local static variables initialized like other global variables - at the start of program execution? Or do local static variables differ from normal globals, and only get initialized once their function/block is called/reached?
C17 6.2.4 (3)
An object whose identifier is declared without the storage-class specifier _Thread_local, and either
with external or internal linkage or with the storage-class specifier static, has static storage duration.
Its lifetime is the entire execution of the program and its stored value is initialized only once, prior
to program startup.
However, remember the as-if rule. An implementation could wait to initialize the variable until the first call to the function, as a conforming program has no way to access its value before then, and so would not be able to tell the difference.
If you have an implementation with extensions or implementation-defined behavior that do provide a way to access the variable before the first call to the function, then such an implementation ought to document whether you would see the initialized value in such a case. In most cases I would expect the answer to be "yes".
The most common implementation I'm familiar with is to load the initial value from the executable, or to place it in a bss section that is zeroed at startup, just as is done for global or file-scope static variables.
Although implementation dependent, static variables - any scope - are initialized as the executable is loaded.

How do static variables in C persist in memory?

We all know the common example to how static variable work - a static variable is declared inside a function with some value (let's say 5), the function adds 1 to it, and in the next call to that function the variable will have the modified value (6 in my example).
How does that happen behind the scene? What makes the function ignore the variable declaration after the first call? How does the value persist in memory, given the stack frame of the function is "destroyed" after its call has finished?
static variables and other variables with static storage duration are stored in special segments outside the stack. Generally, the C standard doesn't mention how this is done other than that static storage duration variables are initialized before main() is called. However, the vast majority of real-world computers work as described below:
If you initialize a static storage duration variable with a value, then most systems store it in a segment called .data. If you don't initialize it, or explicitly initialize it to zero, it gets stored in another segment called .bss where everything is zero-initialized.
The tricky part to understand is that when we write code such as this:
void func (void)
{
static int foo = 5; // will get stored in .data
...
Then the line containing the initialization is not executed the first time the function is entered (as often taught in beginner classes) - it is not executed inside the function at all and it is always ignored during function execution.
Before main() is even called, the "C run-time libraries" (often called CRT) run various start-up code. This includes copying down values into .data and .bss. So the above line is actually executed before your program even starts.
So by the time func() is called for the first time, foo is already initialized. Any other changes to foo inside the function will happen in run-time, as with any other variable.
This example illustrates the various memory regions of a program. What gets allocated on the stack and the heap? gives a more generic explanation.
The variable isn't stored in the stack frame, it's stored in the same memory used for global variables. The only difference is that the scope of the variable name is the function where the variable is declared.
Quoting C11, chapter 6.2.4
An object whose identifier is declared [...] with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
In a typical implementation, the objects with static storage duration are stored either in the data segment or the BSS (based on whether initialized or not). So every function call does not create a new variable in the stack of the called function, as you might have expected. There's a single instance of the variable in memory which is accessed for each iteration.

Assignment to static variable is ignored

I have following piece of code:
#include <stdio.h>
int f1()
{
static int s=10;
printf("s=%d\n",s++);
}
int main()
{
f1();
f1();
return 0;
}
The output is:
s=10
s=11
Why is the line static int s=10 ignored at the second time, when f1 is called?
That is no assignment, but an initializer. Local static variables are only initialized once at program startup like global variables. They keep their last assigned value even between invocations of the function. Thus after your first call, it retains the value 11. In fact, they are like file-scope static variables, with their name only known in the scope of the block they are declared (but you can pass them by pointer).
Drawback is they only exist once. If you invoke the same function from multiple threads, they all share the same variable.
Try a third call: you will get 12.
Note: the initializer must be a constant expression. Try static int s = 10, t = s + 5; and read the compiler error message.
Initialization of a static variable is one-time (with the time of initialization guaranteed to occur before the first call, which could occur at compile time or at run time; compiler dependent). That's the main reason to use them.
The static variables are initialized only once, conceptually even before application has started.
From C11 (N1570) §5.1.2/p1 Execution environments:
All objects with static storage duration shall be initialized (set to
their initial values) before program startup.
along with §6.2.4/p3 Storage durations of objects:
Its lifetime is the entire execution of the program and its stored
value is initialized only once, prior to program startup.
As others have said, a static variable at function scope is initialized only once. So the assignment doesn't happen on subsequent calls to the function.
Unlike other local variables, a static local is not defined on the stack but in the data segment, probably in the same location as global variables. Globals are also initialized at application startup (they have to, since they don't live inside of a function and therefore can't be executable code), so conceptually you can think of a static variable as a global variable with limited visibility.
From the C89 Standard HTML version at 3.1.2.4 Storage durations of objects it specifies:
An object declared with external or internal linkage, or with the storage-class specifier static has static storage duration. For such an object, storage is reserved and its stored value is initialized only once, prior to program startup. The object exists and retains its last-stored value throughout the execution of the entire program
(The emphasis is mine)
So it says that everytime you use the static qualifier, that variable preserves its value across multiple function calls.
Local variables that are not static are initialized everytime you call the function that delcares them, so they do not preserve their value across function calls.
Hope this helped!

Is it correct to call a static variable local?

It is known that the C language supports two kinds of memory allocation through the variables in C programs:
1) Static allocation is what happens when you declare a static
variable. Each static variable defines one block of space, of a fixed
size. The space is allocated once, when your program is started, and
is never freed.
2) Automatic allocation happens when you declare an automatic
variable, such as a function argument or a local variable. The space
for an automatic variable is allocated when the compound statement
containing the declaration is entered, and is freed when that compound
statement is exited.
(this is a full quote from http://www.cs.utah.edu/dept/old/texinfo/glibc-manual-0.02/library_3.html)
The question is: is it correct to call a static variable in a function "local" in terms of memory allocation and why?
Thanks to everyone in advance.
P.S. any quotes from the C standard are welcome.
C standard doesn't define the term of local variable. Automatic and static refer to storage duration.
C11 (n1570), § 6.2.4 Storage durations of objects
An object has a storage duration that determines its lifetime.
You could call it a "function-local static variable" or something like that, but if you simply call it a "local variable" you may find that people are surprised when they find out it's actually static, and therefore has some of the properties of a global variable.
There are two types of static variables in C.
The global static variables, where the static states that these variables can only be seen in this translation-unit.
Static variables with a local scop (i.e. in function). These are initialized once and keep their value event after going out of scope.
And to you question: no, a variable can't be static and automatic at the same time.
If you check their addresses, you will se that the static variable does not live on the current stack frame.
In the context of variables, the term local most often denotes visibility and scope rather than the storage mechanism and lifetime.
Using the term local variables in C is in fact inaccurate as the standard never talks about that.
Informally, a static variable inside a function could be said to be local within the visible scope of the function, but not much more than that.
I would suggest against using the term local variables at all. Instead, one should talk about static variables within a function, automatic variables, static variables in the file scope and globals.
The question is: is it correct to call a static variable in a function "local" in terms of memory allocation and why?
Static variables are stored in the data section of the memory allocated to the program.
Even though if the scope of a static variable ends , it can still be accessed outside its
scope , this may indicate that , the contents of data segment , may be independent
of scope.
Example
#include <stdio.h>
int increment(void);
int main()
{
printf("\ni = %d",increment());
printf("\ni = %d",increment());
printf("\ni = %d",increment());
}
int increment(void)
{
static int i = 1;
return i++ ;
}
In the above example , after each function call to increment() , the static variable i inside the function goes out of scope every time the function returns but persistently
retains its value. This is only possible because the variable is not on the same same stack as the function , but it is present entirely in a different memory area , the data segment.

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 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.
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.

Resources