zaro

How are global variables stored?

Published in Memory Management 3 mins read

Global variables are stored in the data segment of a program's memory space.

Here's a more detailed explanation:

When a program is compiled and linked, the compiler allocates specific memory regions to hold different types of data. Global variables, along with static variables, are placed in the data segment (sometimes further divided into initialized and uninitialized data segments, like .data and .bss respectively). This area is separate from the code segment (where the program's instructions reside) and the stack and heap (used for dynamic memory allocation during runtime).

Understanding the Data Segment

The data segment is a crucial part of a program's memory layout. It contains:

  • Initialized Data: Global and static variables that have a specific initial value assigned to them at compile time. These values are loaded into memory when the program starts.

  • Uninitialized Data (BSS): Global and static variables that do not have an explicit initial value. These variables are initialized to zero by the operating system before the program begins execution. This is usually more efficient than storing many explicit zeros in the executable file.

Implications of Global Variable Storage

The way global variables are stored has several implications:

  • Scope: Global variables are accessible from anywhere in the program's code, subject to any scope limitations imposed by the programming language (e.g., file-level scope in C).

  • Lifetime: Global variables persist throughout the entire execution of the program. Their memory is allocated when the program starts and deallocated when the program terminates.

  • Address Space: Global variables reside within the virtual address space of the process. They are part of the process's data segment and are managed by the operating system's memory management system.

Example

Consider a simple C program:

#include <stdio.h>

int global_variable = 10;  // Initialized global variable
int uninitialized_global;   // Uninitialized global variable (BSS)

int main() {
    printf("Global variable: %d\n", global_variable);
    printf("Uninitialized global: %d\n", uninitialized_global); // Will print 0

    return 0;
}

In this example, global_variable will be stored in the initialized data segment (.data), and uninitialized_global will be stored in the uninitialized data segment (BSS).

Shared Libraries

As the provided reference correctly points out, global variables in shared libraries (or shared-object files) behave in much the same way. They reside in the data segment of the shared object file that is mapped into the virtual address space of the process. Each process using the shared library receives its own private copy of those variables due to the copy-on-write nature of shared libraries. Thus, global variables in a shared library exist within the address space of a virtual processor (VP) not the thread itself.