Skip to content
Step 6 of 105–7 minutes

How Does a Program Live in Memory?

When the operating system runs a program, it does not throw variables and code into memory randomly. Instead, it assigns the program an isolated memory block called an address space, neatly partitioned into four standard segments: Code, Data, Heap, and Stack.

Understanding this layout explains why functions have local variables, how dynamic memory works, and what causes crashes like "Stack Overflow" or "Memory Leaks".

Stack vs Heap: What Is the Difference?

The Stack is managed automatically by the CPU hardware for function calls. It is lightning-fast but fixed in size.The Heap is for large, flexible data whose size is only known while running (like loading a 10MB JPEG image). It requires allocation and cleanup.

The Cafeteria Tray Analogy (LIFO)

Think of the Stack like a spring-loaded stack of cafeteria trays: When a function is called, a new tray is pushed on top. The CPU only ever works on the top tray. When the function finishes, that tray is popped off, instantly revealing the previous function underneath.

// C Program demonstrating the 4 Memory Segments:
int global_count = 10;           // -> DATA SEGMENT (Global variable, fixed size)

void square(int n) {
    int sq = n * n;              // -> STACK SEGMENT (Local variable inside square's frame)
}

int main() {
    int a = 15;                  // -> STACK SEGMENT (Local variable inside main's frame)
    char *buffer = malloc(64);   // -> 'buffer' pointer is on STACK; 64 bytes are on HEAP!
    square(a);
    free(buffer);                // -> HEAP SEGMENT  (Freed manually to prevent memory leak)
    return 0;                    // -> CODE SEGMENT  (Executable instructions in text segment)
}

Why Do Stack and Heap Grow Toward Each Other?

A running program cannot predict whether it will need deep function recursion (more stack) or large data downloads (more heap). By putting the Stack at high memory growing down and the Heap at low memory growing up, both can share the large unallocated middle pool flexibly without wasting fixed partitions!

The Pointer Duality: Stack Variable vs Heap Block

Notice char *buffer = malloc(64);. The variable buffer itself is an 8-byte address stored on the Stack. The 64 bytes of memory it points to reside in the Heap. Freeing the buffer cleans up the heap space.

Live Memory Animator

Process Address Space & Call Stack

High Address (0x7FFF FFFF)Stack grows ↓
Stack Segment (Calls & Locals)Empty
↕ Free Memory Pool ↕
Heap Segment (Dynamic malloc)No active allocations
Data Segment: global_count = 10
Code Segment (Text): main, square (Read-Only)
Low Address (0x0000 0000)Heap grows ↑
Execution State (Step 1 of 7):

Before execution: No function is running yet. The Stack and Heap are empty.

Code and Data segments are loaded into RAM.

Stack Segment

Stores local variables and active function call frames. Grows downward automatically as functions are called and shrinks as they return.

Heap Segment

Stores dynamic memory allocated at runtime (e.g. malloc in C, new in Java/JS). Grows upward toward the stack.

Data Segment (Globals)

Stores global and static variables declared outside functions. Allocated once when the program launches and exists until termination.

Code (Text) Segment

Contains the raw binary machine code instructions executed by the CPU. Marked read-only by the OS to prevent self-modifying code crashes.

How Different Languages Handle Heap Memory

Not all languages handle the Heap identically:

Manual Memory Management (C / C++ / Rust)

The programmer explicitly requests heap memory with malloc() and must remember to release it with free(). If you forget to free memory, your program leaks RAM. Rust uses compile-time ownership rules to free memory automatically without leaks.

Automatic Garbage Collection (Java / Python / JS)

You never call free(). A background runtime thread called the Garbage Collector (GC) periodically inspects the Heap, finds objects that no longer have any variables pointing to them, and reclaims their memory automatically.

Common Beginner Misconceptions

  • "A Stack Overflow is just an internet forum."
    Reality: The forum was named after a fatal computer hardware trap! The Stack has a fixed maximum size (typically 1MB to 8MB). If a recursive function calls itself without terminating, it keeps pushing frames until it hits an unmapped OS Guard Page. The CPU immediately halts the process with a fatal Segmentation Fault (SIGSEGV).
  • "Variables created inside a function persist after it returns."
    Reality: Local variables only exist while that specific function’s stack frame is active. The microsecond the function hits return, the CPU adjusts the Stack Pointer (pops the frame), immediately invalidating those variables.
  • "malloc() allocates memory on the Stack."
    Reality: malloc() always allocates bytes on the Heap. Only the pointer variable holding the heap’s memory address resides on the Stack!
Active Learning — Trace Memory State

In the C program above, function square(n) creates a local variable 'int sq = n * n'. What happens to the memory occupied by 'sq' the moment square() finishes executing and returns?

Lesson 06 Key Takeaways

  • A process address space has 4 segments: Code, Data, Heap, and Stack.
  • The Stack manages function calls and local variables automatically via LIFO frames.
  • The Heap stores dynamic data and requires manual cleanup (C) or a Garbage Collector (JS/Java).
Notessaved locally+

Notes stay in this browser. They are not uploaded.

Suggest an edit

Learning graph

Discussion

0 comments

Loading discussion…

Sign in to ask a question.