← 🧠 Storage Classes, Scope & Memory
Subtopic 3 of 5

6.3Memory layout of a C program

The idea

A running program's memory is split into code, data/BSS, heap and stack. Where a variable lives decides its lifetime.

Think of it like this: A building: the code is the architect's plans, globals are the permanent fixtures, the heap is a storeroom you rent from, and the stack is the desk you clear after each task.

Why it exists

Questions ask where a variable is stored, or relate this to compilers and operating systems.

How it works

  1. Globals and statics: data (with value) or BSS (zero-filled).
  2. Locals and parameters: the stack, one frame per call.
  3. malloc'd blocks: the heap, until free.
  4. Machine instructions: code (text), read-only.

Worked example: int *p = malloc(40) in a function

The pointer p is a local, so it lives on the stack. The 40 bytes it points to live on the heap.

Now play with it

  • →Click each region of the diagram, then do the "Where does it live?" quiz.

High addresses at the top. Click a region.

Stack

Local variables, parameters, return addresses. One frame per active call. Grows toward lower addresses.

int x inside a function; function arguments; a local array

Where does it live? · question 1 of 7

a local variable int x declared inside a function

Check yourself

Where is a static int count; declared inside a function stored?

Remember: Stack = locals; heap = malloc; data/BSS = globals and statics; code = instructions.
Exam notes (the dense version)

Low to high addresses: code (text), initialised data, uninitialised data (BSS, zeroed), then the heap (grows up, malloc) and the stack (grows down, locals). Globals and static variables live in data/BSS; locals and parameters live on the stack; malloc'd memory lives on the heap and stays until free.

Previous year questions: Storage Classes, Scope & Memory (8)

PYQs are grouped by topic, so this is the full set for Storage Classes, Scope & Memory; try the ones that match this subtopic. Open all 8 on the topic page.