Where are local static variables inside a function stored - in the data segment, or on the stack?

Viewed 115
#include <stdio.h>
 
void f (void)
{
    static int count = 0;   // static variable   
    int i = 0;              // automatic variable
    printf("%d %d\n", i++, count++);
}
 
int main(void)
{
    for (int ndx=0; ndx<10; ++ndx)
        f();
}

For example, in this code, where is count stored? Usually, static variables will be stored in the Data segment, and local variables are stored on the stack.

1 Answers

Formally, variables declared inside of a function as static have static storage duration, which means their lifetime is the lifetime of the entire program.

The C standard says nothing about stacks or segments as those are implementation details. That being said, on Linux initialized static variables are typically placed in the .data section while uninitialized or 0 initialized variables are stored in the .bss section.

Related