Memory safety

On this page 7

Memory safety is the property of a program or language that guarantees every memory access targets a valid, live object within its bounds and with the correct type. In cybersecurity, memory safety matters because its absence produces the most exploited class of vulnerabilities: buffer overflows, use-after-free, double free and out-of-bounds reads that let attackers leak data or achieve remote code execution.

Large vendors have repeatedly reported that roughly 60 to 70 percent of their severe security bugs in C and C++ code bases are memory safety errors. This share explains why government agencies and industry now promote a transition to memory-safe languages as a structural fix rather than continuing to patch individual flaws.

Spatial and temporal memory safety

Memory safety has two main dimensions. Spatial safety ensures that accesses stay within the bounds of the object they refer to, so writing past the end of an array is impossible. Temporal safety ensures that an object is accessed only while it is alive, so a pointer cannot be used after the memory it refers to has been freed or reused.

Some definitions add type safety, which prevents memory from being interpreted as an incompatible type, and initialization safety, which prevents reading uninitialized memory. In concurrent programs, data race freedom is closely related, because unsynchronized writes can corrupt memory in ways that break the other guarantees.

The following table maps each dimension to the vulnerability classes it prevents, using common CWE categories.

DimensionGuaranteeVulnerability classes prevented
Spatial safetyAccess stays within object boundsBuffer overflow, out-of-bounds read and write
Temporal safetyAccess only during object lifetimeUse-after-free, double free, dangling pointer
Type safetyMemory read as its real typeType confusion
Initialization safetyNo reads of uninitialized dataInformation leaks, undefined behavior
Data race freedomSynchronized shared accessRace-induced memory corruption
Memory safety dimensions and the bugs they prevent

How memory errors become exploits

A memory error becomes an exploit when an attacker can control what is written or read at an invalid location. In C and C++, such accesses are undefined behavior: the language makes no promise, and the compiled program simply touches whatever memory lies at the computed address.

A stack buffer overflow can overwrite a saved return address and redirect execution. A use-after-free lets an attacker allocate a controlled object in freed memory, so a stale pointer then operates on attacker data, often a fake virtual function table. An out-of-bounds read, as in Heartbleed, can leak keys and session data without corrupting anything.

Modern exploits frequently chain several weaknesses: an information leak defeats address randomization, and a write primitive then hijacks control flow. This chaining is why even seemingly minor memory bugs receive high CVSS scores.

How languages provide memory safety

Languages achieve memory safety through runtime checks, automatic memory management or compile-time ownership rules, and each approach carries different costs. The table below compares the main families.

Language familyMechanismTypical costEscape hatch
C and C++None by defaultNo safety overheadEntire language is unchecked
RustOwnership, borrowing and lifetimes checked at compile timeSteeper learning curveunsafe blocks
Java, C# and GoGarbage collection plus bounds checksCollector pauses and memory overheadJNI, unsafe packages
SwiftAutomatic reference counting plus bounds checksReference counting overheadUnsafe pointer types
Python and JavaScriptManaged runtimeInterpreter or JIT overheadNative extensions
Memory safety approaches across languages

Rust is notable because it delivers temporal safety without a garbage collector. The borrow checker proves at compile time that no reference outlives its object and that mutable access is exclusive, which also rules out data races in safe code. Bugs remain possible inside unsafe code, so auditors concentrate review on those blocks.

Every memory-safe language still depends on native code at its boundary: runtimes, foreign function interfaces and operating system kernels. Memory safety therefore reduces the exploitable surface dramatically but does not reduce it to zero.

Hardening code that is not memory safe

Because billions of lines of C and C++ cannot be rewritten quickly, defenders combine mitigations, testing tools and safer subsets. Mitigations make exploitation harder but do not remove the underlying bug, which is the key distinction from true memory safety.

MeasureTypeWhat it doesMain limitation
ASLRMitigationRandomizes memory layoutDefeated by information leaks
Stack canariesMitigationDetects return address overwriteDoes not cover heap bugs
Control-flow integrityMitigationRestricts indirect jump targetsData-only attacks bypass it
AddressSanitizerTesting toolDetects out-of-bounds and use-after-freeToo slow for production
FuzzingTesting methodFinds crashes with generated inputsCoverage is never complete
Memory taggingHardware featureTags pointers and memory regionsProbabilistic, needs recent CPUs
Mitigations and tools for unsafe code

Hardware approaches such as Arm Memory Tagging Extension and the CHERI capability architecture move checks into the processor. CHERI in particular enforces spatial safety deterministically through capabilities, although adoption is still limited.

Policy, migration and common misconceptions

Security agencies, including CISA and the NSA, publish guidance urging vendors to adopt memory safety roadmaps. The realistic strategy is to write new components in memory-safe languages while hardening legacy code, because vulnerability density is highest in recently written code.

  • Misconception: modern C++ is memory safe. Smart pointers and containers help, but iterators, references and raw pointers can still dangle.
  • Misconception: memory-safe code is bug free. Logic errors, injection flaws and misconfiguration remain fully possible.
  • Misconception: mitigations are equivalent. They raise exploit cost but leave the defect exploitable under the right conditions.
  • Misconception: rewriting everything is required. Targeting parsers, network-facing code and privilege boundaries gives the largest risk reduction first.

The short version

A program stores its data in numbered boxes in memory. Memory safety means the program can only open the boxes that belong to it, and only while they are still in use.

Without that rule, a small mistake can let an attacker read someone else’s box or slip a note into it that changes what the program does. Languages with memory safety check these rules automatically, which removes a whole family of attacks instead of fixing them one at a time.

Where it makes a difference

A company that builds a mobile operating system tracked its security bugs for several years. Most severe issues came from media codecs and network parsers written in C++, where malformed files triggered out-of-bounds writes and use-after-free errors.

The engineering team decided to write all new parsing and Bluetooth components in Rust while leaving stable legacy code in place with fuzzing and memory tagging. Over the following releases, new Rust code produced no memory safety vulnerabilities in the affected components, and the share of memory safety bugs among all reported vulnerabilities fell steadily as older code was retired.

The team also found that rewriting only the highest-risk input-handling code delivered most of the benefit, which made the migration affordable without halting feature work.