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.
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.
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.
Questions to ask yourself
- How big is this buffer, and who controls the length of what is written into it?
- Can this pointer be used after the owner frees it?
- Can this arithmetic exceed the range of its type, and what happens when it does?
Practise this
- Copying a name into a fixed buffer · Memory and numbers (C, C++, Rust)
- Order total that wraps around · Memory and numbers (C, C++, Rust)
- Using a session after it was freed · Memory and numbers (C, C++, Rust)
- Reading a quantity in Rust · Memory and numbers (C, C++, Rust)
- Logging a username with printf · Memory and numbers (C, C++, Rust)