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

Free lesson

Memory-safe languages and the C that stays

After this lesson: I can explain how a memory-safe language removes a class of bug, using published evidence.

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

Seven in ten

Microsoft and the Chromium project each counted their serious security bugs. Both found about seven in ten were memory safety bugs: the kinds this module has shown.

A whole class that large is better removed by the language than chased one bug at a time.

By the end of this lesson

Note

I can explain how a memory-safe language removes a class of bug, using published evidence.

Key words

WordWhat it meansExample
Memory-safe languagea language that checks or forbids unsafe memory useRust, Go, Python
Bounds checka check that an index is inside the array
Garbage collectorfrees memory itself once nothing uses it
OwnershipRust's rule that each value has one owner
Roadmapa dated plan to move code to a safer language

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

The language does the checking

A memory-safe language checks every index against the array's length, so an off-by-one stops with a clear error instead of writing past the end.

Python and Go free memory with a garbage collector, so nothing is used after free. Rust proves at compile time that a value is not used once it has gone.

The off-by-one in Python

Command
mkdir -p ~/mem/safe && cd ~/mem/safe && cat > marks.py <<'END'
marks = [0] * 5
try:
    for i in range(6):
        marks[i] = 60 + i
except IndexError as problem:
    print("refused:", problem)
print("marks:", marks)
END
python3 marks.py

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

The badge in Python

Command
mkdir -p ~/mem/safe && cd ~/mem/safe && cat > badge.py <<'END'
import sys
name, room = sys.argv[1], sys.argv[2]
line = f"{name} in {room}"
print(line, len(line))
END
python3 badge.py Christopher-Robinson-Smith Lecture-Theatre-Two

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

The same two bugs in Rust (to read)

Code: rust
fn main() {
    let mut marks = [0; 5];
    for i in 0..6 {
        marks[i] = 60 + i;   // i = 5 stops the program here:
    }                        // "index out of bounds: the len is 5 but the index is 5"
    let note = String::from("bring a pen");
    drop(note);
    // println!("{note}");  // will not compile: note was moved into drop
}

Make a free account to save your work and track your progress.

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

Worked example: what vendors and agencies published

WhoWhat they foundSource
MicrosoftAbout 70% of the CVEs it assigned from 2006 to 2018 were memory safetyMicrosoft Security Response Center, 2019
Chromium projectAround 70% of its serious security bugs since 2015Chromium "Memory safety" page
Android (Google)Memory safety share fell from 76% in 2019 to about 24% in 2024Google Security Blog, September 2024
CISA, NSA, FBI, the UK's NCSC and othersMakers should publish memory-safe roadmaps"The Case for Memory Safe Roadmaps", December 2023

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

New code matters most

Android did not rewrite its old C and C++. It wrote new code in memory-safe languages, mainly Rust and Kotlin.

Most bugs are in new or recently changed code, so the share of memory safety bugs fell as the old code aged. Google gives 2024's figure as an estimate for the year.

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 a memory-safe language makes a program secure. It removes one class of bug, a large one. Logic errors, injection and weak passwords remain, and unsafe Rust or a C library brings the old risks back.

What to do with the C that stays

Most systems keep some C for years. Build it with every hardening flag and audit the binary. Run its tests under the sanitizers, and fuzz anything that reads outside input.

Ban the unsafe calls in review. Move the riskiest parts first: parsers and anything facing the network.

Worked example: a plan for one C codebase

StepWhatWhere this module showed it
1Hardening flags on and audited in every buildLesson 4
2Tests under AddressSanitizer and UBSan in CILesson 2
3No gets, strcpy, sprintf or printf(text) in reviewLesson 5
4Fuzz every parser of outside inputThe fuzzing module
5New parts in a memory-safe language, riskiest firstThis lesson

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

Assignment: plan the move

A team lists its past bugs and its components. Write two functions.

share(bugs) takes a list of bug classes and returns the percentage that are memory safety bugs, rounded to a whole number. The memory safety classes are "overflow", "use-after-free", "double-free" and "uninitialised". An empty list gives 0.

first_to_move(components) takes dictionaries with name, language, untrusted (reads outside input, a bool) and lines. Return the names of the C and C++ components only ("c" or "c++"), untrusted ones first, then by more lines first, then by name.

Code: python
def share(bugs):
    return 0


def first_to_move(components):
    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.