Where does a variable actually live?
You write int count = 3; and the program runs. The number is stored somewhere in memory, at an address.
A global, a string, a block from malloc and a local each go to a different part. Knowing the parts is how you read every memory bug report later.
By the end of this lesson
Note
I can name the part of a process's memory each kind of variable lives in.
Key words
| Word | What it means | Example |
|---|---|---|
| Process | a program while it runs | |
| Segment | one part of a process's memory with one job | |
| Stack | memory for a function's local variables | |
| Heap | memory a program asks for while it runs | malloc(64) |
| Memory map | the list of a process's regions | /proc/self/maps |
| Permissions | whether a region may be read, written or run | r-xp |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsA process has six main parts
The code holds the machine instructions. Read-only data holds constants such as string literals. Data holds globals given a starting value; bss holds globals that start at zero.
The heap grows as the program calls malloc. The stack holds each function's locals and is reused as calls return.
Write layout.c, part 1
mkdir -p ~/mem/layout && cd ~/mem/layout && cat > layout.c <<'END'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int visits = 7;
int total;
const char motto[] = "read before you write";
int main(void) {
int count = 3;
char *note = malloc(64);
char line[256];
ENDShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write layout.c, part 2, and run it
cd ~/mem/layout && cat >> layout.c <<'END'
printf("code main %p\n", (void *)main);
printf("rodata motto %p\n", (void *)motto);
printf("data visits %p\n", (void *)&visits);
printf("bss total %p\n", (void *)&total);
printf("heap note %p\n", (void *)note);
printf("stack count %p\n", (void *)&count);
FILE *maps = fopen("/proc/self/maps", "r");
while (fgets(line, sizeof line, maps))
if (strstr(line, "layout") || strstr(line, "[heap]") || strstr(line, "[stack]"))
fputs(line, stdout);
free(note);
return 0;
}
END
gcc -g -o layout layout.c && ./layoutShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsThe file already has the same parts
Code, read-only data, data and bss are in the program file before it runs. The heap and the stack only exist once it runs.
size adds up each part of the file. readelf -S lists the sections by name. gdb can say which section a symbol is in.
Measure the parts with size
cd ~/mem/layout && size layoutShown here, not run. Press Start lab to type it into your own lab’s terminal.
List the four sections
cd ~/mem/layout && readelf -SW layout | grep -E ' \.(text|rodata|data|bss) 'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Ask gdb where each symbol is
cd ~/mem/layout && gdb -q -batch -ex 'info symbol main' -ex 'info symbol &motto' -ex 'info symbol &visits' -ex 'info symbol &total' ./layoutShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsEach region has permissions
Each line of the memory map ends with what may happen there: r read, w write, x run as code.
The code is r-x: readable and runnable, never writable. The heap and the stack are rw-: writable, never runnable. Lesson 3 shows why that split matters.
Print each region's permissions
cd ~/mem/layout && ./layout | grep -E '^[0-9a-f]+-' | awk '{print $2, $6}'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think a variable has one fixed address. The heap and the stack move every time the program starts. Run it twice: compare the addresses, never write them down as facts.
Run it twice and compare
cd ~/mem/layout && ./layout | grep -E '^(heap|stack)'; ./layout | grep -E '^(heap|stack)'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Worked example: where layout.c keeps each thing
| In the code | Part | Permissions | Exists in the file? |
|---|---|---|---|
| main | Code (.text) | r-x | Yes |
| motto, a const string | Read-only data (.rodata) | not writable | Yes |
| visits = 7 | Data (.data) | rw- | Yes |
| total, no value | Bss (.bss) | rw- | Only its size |
| malloc(64) | Heap | rw- | No |
| count, a local | Stack | rw- | No |
The cells students fill in are left blank in this preview.
Why this matters for memory bugs
A memory bug is a read or write outside the block it was meant for. A sanitizer report says which part the address was in: a stack buffer, a heap block or a global.
Lesson 2 reads those reports, so knowing the parts is the first step.
Assignment: read a memory map
Each line of /proc/<pid>/maps is an address range, permissions, an offset, a device, an inode and sometimes a name. Write two functions.
parse(line) returns a dictionary with start and end (ints, read from hexadecimal), perms (such as "r-xp") and name (the last field, or "" when there is none).
region_of(lines, address) returns the name of the region whose range holds the address (start <= address < end), "anonymous" when that region has no name, or None when no region holds it.
def parse(line):
return {}
def region_of(lines, address):
return None
Make a free account to save your work and track your progress.
Exit quiz
Have a go