The process memory layout
What you'll learn: You will understand how a running program organizes its data into distinct segments like the Stack, Heap, and Data sections.
When you run a C program, the operating system doesn't just toss your code into a random pile of RAM. It creates a "Process" and neatly organizes its memory into a specific layout. Think of it like a library: there’s a section for the books (code), a section for the reference desk (global variables), and a section for the study tables where people drop off and pick up bags (temporary data).
The four main segments
Every C process is divided into these primary areas:
- Text Segment: This is where your compiled machine code lives. It is usually "read-only" to prevent the program from accidentally modifying its own instructions.
- Data Segments (Initialized & BSS): This is the home for global and
staticvariables. If you give a global variable a value (likeint x = 10;), it goes in the Initialized Data segment. If you don't, it goes in the "BSS" segment, which the OS clears to zero. - The Stack: This is for local variables and function calls. It grows and shrinks automatically as you enter and exit functions. It’s fast but has a limited size.
- The Heap: This is the "free pool" of memory. When you use
malloc(), you are requesting space here. You are responsible for cleaning it up.
Visualizing the layout in code
Here is how a simple C file maps to these memory regions:
#include <stdio.h>
#include <stdlib.h>
int global_var = 100; // Initialized Data Segment
int uninitialized_var; // BSS Segment
int main() {
int stack_var = 5; // The Stack
// The Heap (memory requested at runtime)
int *heap_var = malloc(sizeof(int));
*heap_var = 20;
printf("Code is in Text Segment\n");
free(heap_var);
return 0;
}
The "Growing" Problem
An interesting feature of this layout is that the Stack and the Heap usually grow toward each other from opposite ends of the available memory space. The Stack grows "down" from high addresses, and the Heap grows "up" from low addresses. If they ever meet, your program has run out of memory, leading to a crash or a stack overflow.
Key takeaway
A process organizes memory into the Text (code), Data (globals), Stack (local variables), and Heap (dynamic memory) segments to keep execution efficient and secure.