Automatic storage duration on the stack
What you'll learn: How C automatically manages memory for local variables using a temporary storage area called the stack.
The self-cleaning desk
Imagine your computer's memory as a giant warehouse. In this warehouse, the stack is a small, high-speed workbench right next to the assembly line. When a function starts running, C clears off a specific amount of space on that workbench for that function's variables.
This is known as automatic storage duration. You don't have to ask for this memory, and you don't have to clean it up. The moment the function finishes, C effectively "swipes" the workbench clean, reclaiming that space for the next function.
How it works in code
Every variable you declare inside a function (without special keywords like static) lives on the stack. These are called "local variables."
#include <stdio.h>
void cook_meal() {
// These variables are placed on the stack
int heat_level = 5;
float timer = 10.5f;
printf("Cooking at level %d...\n", heat_level);
// As soon as this function reaches the '}',
// heat_level and timer are automatically deleted.
}
int main() {
cook_meal();
// The memory used by cook_meal is already gone by this point.
return 0;
}
Why the stack?
The stack is incredibly fast because it follows a "Last-In, First-Out" (LIFO) order. Think of it like a physical stack of dinner plates. When you call a function, you put a new plate on top containing its variables. When the function ends, you pop that plate off.
The computer doesn't have to search for an empty spot in the warehouse; it always knows the next piece of memory is right on top.
However, there is a trade-off: the stack is small. If you try to create a massive array (like one billion integers) on the stack, you might run out of room, causing a "stack overflow." For everyday variables like integers, characters, and small arrays, the stack is your best friend because it handles the housekeeping for you.
Key takeaway
Local variables have automatic storage duration, meaning they are created on the stack when a function starts and are instantly destroyed when the function ends.