Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

How a program lays out its memory

After this lesson: I can name the part of a process's memory each kind of variable lives in.

60 min lesson7 commandsCompilers and computer architecture lab: gcc, flex, bison and RISC-V in one VM

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

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

WordWhat it meansExample
Processa program while it runs
Segmentone part of a process's memory with one job
Stackmemory for a function's local variables
Heapmemory a program asks for while it runsmalloc(64)
Memory mapthe list of a process's regions/proc/self/maps
Permissionswhether a region may be read, written or runr-xp

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A 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

Command
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];
END

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Write layout.c, part 2, and run it

Command
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 && ./layout

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The 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

Command
cd ~/mem/layout && size layout

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

List the four sections

Command
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

Command
cd ~/mem/layout && gdb -q -batch -ex 'info symbol main' -ex 'info symbol &motto' -ex 'info symbol &visits' -ex 'info symbol &total' ./layout

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Each 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

Command
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

Command
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 codePartPermissionsExists in the file?
mainCode (.text)r-xYes
motto, a const stringRead-only data (.rodata)not writableYes
visits = 7Data (.data)rw-Yes
total, no valueBss (.bss)rw-Only its size
malloc(64)Heaprw-No
count, a localStackrw-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.

Code: python
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

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.