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

Free lesson

Finding memory bugs with sanitizers

After this lesson: I can use AddressSanitizer to find a memory bug in my own C program.

60 min lesson10 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

It printed the right answer

A marks program fills five places and prints the first and the last. The answer is right, so the tests pass.

It also wrote a sixth number into memory it never asked for. Nothing crashed today. One day it will, somewhere else, and nobody will know why.

By the end of this lesson

Note

I can use AddressSanitizer to find a memory bug in my own C program.

Key words

WordWhat it meansExample
Buffer overflowa read or write past the end of a block
Use after freeusing a block after giving it back
Compiler warninga message about code that looks wrong-Wall
AddressSanitizera checker that reports bad memory access-fsanitize=address
Sanitizer reportwhat the checker prints when it finds a bug

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

Three bugs that look fine

marks.c loops with i <= 5 over five places, so it writes a sixth. notes.c frees a note and then prints it. names.c copies any name into eight bytes.

Write all three, then build and run them plainly.

Write marks.c

Command
mkdir -p ~/mem/bugs && cd ~/mem/bugs && cat > marks.c <<'END'
#include <stdio.h>
#include <stdlib.h>
int main(void) {
  int *marks = malloc(5 * sizeof(int));
  for (int i = 0; i <= 5; i++)
    marks[i] = 60 + i;
  printf("first %d, last %d\n", marks[0], marks[4]);
  free(marks);
  return 0;
}
END

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

Write notes.c

Command
mkdir -p ~/mem/bugs && cd ~/mem/bugs && cat > notes.c <<'END'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
  char *note = malloc(16);
  strcpy(note, "bring a pen");
  free(note);
  printf("note: %s\n", note);
  return 0;
}
END

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

Write names.c

Command
mkdir -p ~/mem/bugs && cd ~/mem/bugs && cat > names.c <<'END'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
  char *name = malloc(8);
  strcpy(name, argc > 1 ? argv[1] : "ann");
  printf("hello %s\n", name);
  free(name);
  return 0;
}
END

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

Build and run all three plainly

Command
cd ~/mem/bugs && for p in marks notes names; do gcc -g -o $p $p.c; done; ./marks; ./notes; ./names ann; ./names Christopher

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

Warnings catch some bugs before you run

Turn warnings on with -Wall -Wextra, and add -O2 so gcc studies the code more closely. gcc then spots a pointer used after free.

It says nothing about the other two. The sizes are only known when the program runs.

Build all three with warnings on

Command
cd ~/mem/bugs && gcc -Wall -Wextra -O2 -c marks.c notes.c names.c 2>&1 | grep -E '^[a-z]+[.]c:[0-9]+:[0-9]+: warning'

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

A sanitizer checks every access as it runs

Build with -fsanitize=address,undefined. AddressSanitizer puts a guard round every block and checks each read and write. UndefinedBehaviorSanitizer adds checks such as signed overflow.

The program is about twice as slow, so this is a test build only.

Build all three with the sanitizers

Command
cd ~/mem/bugs && for p in marks notes names; do gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -o $p-asan $p.c; done; ls *-asan

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

Run marks with AddressSanitizer

Command
cd ~/mem/bugs && DEBUGINFOD_URLS= ./marks-asan 2>&1 | grep -E 'ERROR|of size|#0|located|SUMMARY'

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

Run notes with AddressSanitizer

Command
cd ~/mem/bugs && DEBUGINFOD_URLS= ./notes-asan 2>&1 | grep -E 'ERROR|of size|freed by|SUMMARY'

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

Run names with a long name

Command
cd ~/mem/bugs && DEBUGINFOD_URLS= ./names-asan Christopher 2>&1 | grep -E 'ERROR|of size|#[01] |SUMMARY'

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

Worked example: reading the marks report

Line of the reportWhat it tells you
ERROR: AddressSanitizer: heap-buffer-overflowThe kind of bug, and that the block was on the heap
WRITE of size 4The program wrote 4 bytes, one int
#0 ... in main .../marks.c:6Where: the first frame in your own file
located 0 bytes after 20-byte regionJust past the end of a block of five ints
SUMMARY: ... marks.c:6 in mainThe one-line version to put in a bug report

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

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

A common mistake

Warning

Many people think the first frame of a report is the bug. Frame #0 is often a library function such as strcpy. Read down to the first frame in your own file: that is the line to fix.

A fuzzer finds the inputs for you

A sanitizer only reports a bug that the inputs reach. names was quiet for ann and failed for Christopher.

A fuzzer tries many inputs on a sanitizer build until one fails, as the fuzzing module shows.

Fix the first two and check again

The loop becomes i < 5, and free moves after the last use of the note. The sanitizer build is the proof: it now runs with no report.

names.c needs a safer copy, which lesson 5 builds.

Fix marks and notes, then check

Command
cd ~/mem/bugs && sed -i 's/i <= 5/i < 5/' marks.c && cat > notes.c <<'END'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
  char *note = malloc(16);
  strcpy(note, "bring a pen");
  printf("note: %s\n", note);
  free(note);
  return 0;
}
END
for p in marks notes; do gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -o $p-asan $p.c; done
DEBUGINFOD_URLS= ./marks-asan; DEBUGINFOD_URLS= ./notes-asan

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

Assignment: triage a report

A sanitizer report is a list of lines. Write two functions that pull out what a bug report needs.

kind_of(lines) returns the word after AddressSanitizer: on the first line holding ERROR: AddressSanitizer: , or "" if there is none.

own_frame(lines, own) returns "file:line" from the first frame line (it starts, after spaces, with #) whose last part, after the final /, starts with a name in the list own. Return "" if none does.

Code: python
def kind_of(lines):
    return ""


def own_frame(lines, own):
    return ""

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.