lessons/memory-and-numbers.md

Lesson 15 of 18

Memory and numbers: C, C++ and Rust

In C and C++, the programmer owns every byte and every limit. Rust moves many of those checks to the compiler, but not all of them.

Remember: Know the size of every buffer, the lifetime of every pointer, and the range of every number before arithmetic. Prefer checked operations and types that encode the rule.

Memory bugs are the most serious class in C and C++: a write past a buffer, a read of freed memory, an integer that wraps. They do not always crash. They can read other users' data, or let an attacker place code. Rust prevents most of them in safe code, but unsafe blocks, unwrap, and silent casts still hide the same problems.

The four bugs to recognise

  • Buffer overflow: a copy without a bound, such as strcpy, gets, or memcpy with an unchecked length.
  • Use after free: a pointer used after delete or free. The memory may already hold someone else's data.
  • Double free: the same memory freed twice, which corrupts the allocator's bookkeeping.
  • Integer overflow: arithmetic that wraps around. The total of price times quantity can become negative.
strcpy(name, input);
snprintf(name, sizeof(name), "%s", input);
Vulnerable: no bound. Fixed: the size of the buffer is passed to the function that writes.
close_session(id);
log_event("closed", s->user);
// fixed: read s->user, then erase
Vulnerable: the session is read after it was deleted. Fixed: read first, then let unique_ptr free it.

Rust: what the compiler does not do

Safe Rust rules out buffer overflows and use after free. It does not rule out a panic from unwrap on user input, or a silent truncation from 'as'. A reviewer checks for unwrap and expect on external data, for 'as' on values that can be large, and for every unsafe block, which has to justify its invariants.

let n: u64 = line.trim().parse().unwrap();
n as u32
Vulnerable: unwrap panics on bad input, and 'as' keeps only the low 32 bits.
Compile with warnings on, and run the tests under a sanitiser: AddressSanitizer for C and C++, the race detector for Go. Many memory bugs are found by a tool faster than by a reader, so know which tool to ask.

Questions to ask yourself

  1. How big is this buffer, and who controls the length of what is written into it?
  2. Can this pointer be used after the owner frees it?
  3. Can this arithmetic exceed the range of its type, and what happens when it does?

Practise this