Memory Safety in C and C++: Preventing the Bugs That Matter

C and C++ give direct control over memory, and with it the ability to read or write memory the program does not own. Large software vendors have reported that memory safety bugs make up the majority of their most serious security vulnerabilities, and government security agencies now urge manufacturers to publish plans for reducing them. Most of these bugs can be found by tools that are free and mature. This article covers the bug classes and a layered defence.

At a glance

ASan
AddressSanitizer detects out-of-bounds access and use-after-free while tests run.
UBSan
UndefinedBehaviorSanitizer flags signed overflow, misaligned access and similar errors.
Fuzzing
Generated inputs drive parsers and protocol handlers into paths no hand-written test reaches.
Hardening
Stack protectors, fortified library calls and ASLR make remaining bugs harder to exploit.

The problem

Memory errors rarely fail cleanly. An overflow may corrupt a neighbouring variable and crash much later, or not at all until an attacker supplies carefully shaped input. Code that passes every functional test can still contain them.

The highest risk sits where untrusted data enters: network protocol parsers, file importers, USB and serial message handlers, and anything that decodes a length field and then trusts it.

Treat every length, index and size that came from outside the program as hostile until it has been checked.

Layering the defences

No single tool finds everything. Compiler warnings and static analysis catch problems in code that is never run; sanitizers catch them in code that is run; fuzzing makes sure the risky code runs with inputs nobody thought of. Run AddressSanitizer and ThreadSanitizer in separate builds, since they cannot be combined.

For new components that parse untrusted input, consider a memory-safe language such as Rust behind a C interface. Existing code does not need rewriting to improve: bounds-checked views, smart pointers and hardened standard library modes reduce risk incrementally.

What good looks like

Turn on strict warnings, add a static analyser such as clang-tidy or Cppcheck to CI, and fix or explicitly suppress every finding.

Run the unit and integration tests under AddressSanitizer and UndefinedBehaviorSanitizer on every change, and under ThreadSanitizer for concurrent code.

Write fuzz targets for each parser and message handler with libFuzzer or AFL++, run them continuously, and add every crash found to the regression tests.

Memory bug classes and what finds them
Bug classTypical causeFound by
Buffer overflowUnchecked index or lengthASan, fuzzing, static analysis
Use-after-freeUnclear ownershipASan; prevented by smart pointers
Uninitialised readA path that skips initialisationMemorySanitizer, Valgrind, warnings
Integer overflowSize arithmetic on untrusted valuesUBSan, static analysis
Data raceShared data without synchronisationThreadSanitizer
Double freeTwo owners for one allocationASan; prevented by RAII
Sanitizers are available in Clang and GCC; MemorySanitizer is Clang only.

A layered defence

  1. Coding rules: Ownership and bounds in types
  2. Warnings: Strict flags, treated as errors
  3. Static analysis: Every change, in CI
  4. Sanitizers: Tests under ASan, UBSan, TSan
  5. Fuzzing: Parsers and handlers, continuously
  6. Hardening: Release build protections
Each layer catches bugs the previous one misses.

What it changes

Fewer Vulnerabilities

Bugs that would become security advisories are found during development instead.

Stability

Memory corruption causes many crashes that cannot be reproduced; removing it removes them.

Confidence

Fuzzed parsers handle malformed input from devices and networks predictably.

Evidence

Tool results in CI give customers and assessors something concrete to review.

Where to go next

Build releases with hardening options such as stack protection, fortified library calls and position-independent executables, and keep platform protections such as ASLR and DEP enabled.

Firmware deserves the same treatment. Sanitizers and fuzzers run on the host, so device code that is unit tested off target can benefit from them too.

Problems this prevents

  • Overflows found by attackers, not tests
  • Crashes nobody can reproduce
  • Parsers that trust incoming length fields
  • Data races in concurrent code

Discuss your project

Email support@aavico.com or use Get in Touch when the website finishes loading.