Chapter 01 · Your program’s memory01 / 19

A map of memory

When your program runs, the operating system gives it its own address space: a huge row of numbered bytes, from 0x0 up to 0x7fffffffffff on 64-bit Linux. Every variable, every function and every string lives at some address in that range.

The space is split into regions. Low down sits the text segment, your compiled machine code, and the data segment for global variables. Just above them is the heap, which grows up. Far away at the top is the stack, which grows down.

This lesson is about those two: where your variables live, how long they live, and what breaks when you get it wrong.

Not to scale. About 46 terabytes of addresses lie between the heap and the stack, nearly all of them unmapped. Even mapped memory only gets real RAM when a page is first touched.

the memory map of a running processin the real world
$ cat /proc/self/maps
55a3c7a4b000-55a3c7a4c000 r-xp /usr/bin/cat # text
55a3c7a4e000-55a3c7a4f000 rw-p /usr/bin/cat # data
55a3c8e2f000-55a3c8e50000 rw-p [heap]
7f3b2a428000-7f3b2a5bd000 r-xp libc.so.6
7ffd5e8a5000-7ffd5e8c6000 rw-p [stack]

Linux shows any process’s map in /proc/<pid>/maps (trimmed here). r-x means readable and executable, rw- readable and writable.