What Happens When You Run a C Program ?
What Happens Step by Step …
You run your program (e.g., ./program)
OS loads the program from disk into RAM
CPU reads instructions from RAM and executes them
CPU may:
Do math (+, -, &, ^)
Compare numbers
Jump to a different part of the program
Read/write data in RAM
You use a compiler like gcc or clang: gcc main.c -o main This converts your human-readable code into machine code — a binary file (like main or main.exe).
The compiler:
Parses your code
Allocates memory for variables like int x
Generates instructions that your CPU can run
When you do:
./main
The Operating System (OS):#
Loads the compiled program into memory (RAM)
Sets up:
Stack: for function calls and local variables (int x = 5)
Heap: for dynamic memory (malloc, calloc, etc.)
Text segment: stores machine code (your compiled functions)
Data segment: for global/static variables
Then it starts executing your code line by line using the CPU.
Memory Layout of a C Program in RAM#
Stack ← grows down (local variables)
Heap ← grows up (malloc memory)
BSS Segment (.bss) ← (uninitialized globals)
Data Segment (.data) ← (initialized globals)
Text Segment (.text) ← (compiled code / instructions)
Stack
📌 Stores: Function call info, local variables, return addresses
Heap
📌 Stores: Dynamically allocated memory (malloc, calloc, new in C++)
BSS Segment (.bss)
📌 Stores: Global and static variables that are uninitialized or initialized to zero
Data Segment (.data)
📌 Stores: Global and static variables that are initialized
Text Segment (.text)
📌 Instructions like printf("x = %d", x); are here
Now example in C code#
#include <stdio.h>
int g = 1; // → .data
static int s; // → .bss (uninitialized static)
int main() {
int x = 5; // → stack
int *p = malloc(sizeof(int)); // → heap
*p = 10;
printf("x = %d\n", x); // → .text for instructions
return 0;
}
| Variable | Memory Segment |
|---|---|
x | Stack |
p (pointer) | Stack |
*p (value) | Heap |
g | Data (.data) |
s | BSS (.bss) |
printf | Text (.text) |
Read other posts