Memory & Pointers

the memory segments (text, data, BSS, stack, heap)

/ BSS: bee-ess-ess /

When a program runs, the operating system does not give it one undifferentiated blob of memory — it lays the address space out into neighbourhoods, each with a job and its own rules. Knowing the five classic regions tells you where any given thing lives and why some addresses are writable, some read-only, some grow, and some shrink.

The five at a glance, low addresses to high. Text (also called the code segment) holds the program's machine instructions; it is read-only so the running code cannot rewrite itself. Data holds global and static variables that start with a non-zero value, copied from the executable file. BSS holds global and static variables that start at zero — the file does not store a block of zeros, it just records the size, and the loader zeroes the region (which is why uninitialised globals are reliably 0). The heap is the region for dynamic allocation; it grows upward, toward higher addresses, as you ask for memory. The stack holds function-call frames — local variables, return addresses — and grows the other way, downward, as calls nest. The heap rising and the stack falling toward each other leaves a large free gap between them.

This map explains everyday facts. A string literal lives in read-only memory, so trying to modify it crashes; a local variable lives on the stack and vanishes when its function returns; a global lives in data or BSS and persists for the whole run; and a malloc'd block lives on the heap until you free it. The exact mechanics — how stack frames are built, how the heap is managed — are the next entries; this is the overview that holds them together.

int g = 7; (data) and int z; (BSS, zero-initialised) are globals; inside a function, int local; lives on the stack, and char *p = malloc(100); puts p's 100 bytes on the heap while p itself is a local on the stack.

Globals in data/BSS, locals on the stack, malloc'd blocks on the heap.

These are the classic logical segments of one process's address space, a simplification of how a real ELF executable and a running process are organised. They sit in virtual memory, not fixed physical chips — how virtual maps to physical comes later in Field l. The names text/data/BSS are historical but still universal.

Also called
program memory layoutsegments記憶體佈局