Virtual Memory & Memory Mapping

the address-space layout

Each process gets its own large virtual address space, and that space is not a featureless flat field — it is laid out into regions, each with a job. From low addresses to high you typically find the program's code, then its global data, then a heap that grows upward, a large gap, and near the top a stack that grows downward, with shared libraries and memory mappings sitting in the middle gap. Knowing this map is knowing where a pointer 'is' and why two regions grow toward each other.

Walking it concretely on a typical layout: the lowest mapped area holds the text segment (the machine code, mapped read-and-execute, not writable), then the read-only and read-write data segments (initialised globals, then the zero-initialised bss). Above that the heap begins and grows toward higher addresses as malloc() asks for more (historically via the program break). Far up near the top sits the stack, which grows downward toward lower addresses as functions are called and call frames are pushed. The wide region between heap and stack is where shared libraries and mmap() mappings are placed. The deliberate empty space between the upward-growing heap and the downward-growing stack is what lets each expand without immediately colliding.

One more thing worth naming without diving in: on modern systems the starting positions of these regions are randomised each run — this is address space layout randomisation (ASLR). The point is security: if an attacker cannot predict where the stack, heap, or libraries will land, exploits that depend on hard-coded addresses are much harder to pull off. That is why two runs of the same program print different addresses from the same &x. The layout is conceptually fixed in shape, but shifted by a random offset every time it starts.

In one run a local variable might sit near the top (high stack address like 0x7ffd...) while malloc() returns a much lower heap address (like 0x55a3...). The big numeric gap between them is the empty middle the heap grows up into and the stack grows down into.

Stack high and growing down, heap low and growing up, gap between.

The classic 'stack at the top, heap below' picture is the shape, but ASLR randomises the actual base addresses each run, so do not hard-code or assume any address. Also note this is virtual layout — every process has its own, all overlapping in physical RAM through translation.

Also called
process memory layoutvirtual address-space mapmemory map記憶體配置圖