Course contentsShow
← C
Lesson 149 of 1,2192. Variables and TypesFree lesson

Memory segments: Stack vs. Data

Memory segments: Stack vs. Data

What you'll learn: You will understand how C differentiates between variables that persist for the life of the program and those that are temporary.

When your C program runs, the computer sets aside different "neighborhoods" in memory for your variables. Even though they all store bits and bytes, the location determines how long a variable lives and who can access it.

The Data Segment: The Long-Term Residents

Think of the Data Segment as a sturdy filing cabinet. When you declare a variable outside of any function (a global variable) or use the static keyword, it gets a permanent drawer here the moment your program starts.

These variables are "long-term residents." They are initialized once and stay in memory until you click the exit button on your program. If you change a value in the Data Segment, that change persists even after functions finish running.

The Stack: The Busy Workbench

The Stack is more like a messy, fast-moving workbench. When you call a function, C clears a small space on the workbench for that function's local variables.

These are "temporary workers." As soon as the function reaches its closing curly brace }, the workbench is cleared, and those variables are instantly destroyed to make room for the next task. This is why a variable created inside main() cannot be seen by a variable inside calculateTotal()—they exist on different parts of the workbench at different times.

Seeing the Difference

Here is how C treats these two locations in code:

#include <stdio.h>

// This lives in the DATA SEGMENT (Global)
// It stays alive for the entire program.
int permanentCount = 0; 

void trackVisit() {
    // This lives on the STACK (Local)
    // It is created and destroyed every time the function runs.
    int temporaryCount = 0; 

    permanentCount++;
    temporaryCount++;

    printf("Global: %d, Local: %d\n", permanentCount, temporaryCount);
}

int main() {
    trackVisit(); // Output: Global: 1, Local: 1
    trackVisit(); // Output: Global: 2, Local: 1
    return 0;
}

In the example above, permanentCount remembers its value because it sits safely in the Data Segment. However, temporaryCount is wiped from the Stack every time the function ends, so it resets to zero every single time the function is called.

Key takeaway

The Data Segment stores permanent variables that last the entire program, while the Stack stores temporary variables that vanish as soon as their function finishes.