Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 80 ยท Secure Coding

Memory Safety and Why Languages Matter

Understand buffer overflows and use-after-free bugs, why memory-safe languages remove whole bug classes, and which hardening flags protect C and C++ code.

A large share of the most serious vulnerabilities of the last decades were not clever logic mistakes. They were memory safety bugs: a program reading or writing memory it should not touch. Buffer overflows, use-after-free and out-of-bounds reads have fueled worms, remote code execution and data leaks such as Heartbleed. Large vendors have reported that around 70 percent of their severe vulnerabilities fell into this category.

This lesson explains, at a conceptual level, what these bugs are, why they happen in some languages and not in others, and what defenders do when they cannot rewrite old code. It is intentionally defensive: the demos use a simulated memory in Python to show the idea, and there is no exploit code. You only need one idea: memory is a long row of numbered bytes. Python avoids these bugs, but it has its own pitfalls, covered in Python Security Pitfalls.

What "memory safe" means

In languages like C and C++, a program can ask for a block of memory and then access it through a pointer and an index. The language does not check that the index is inside the block. A memory-safe language (Python, Java, C#, Go, JavaScript, Rust and many others) guarantees that code cannot read or write outside the memory it was given, or use memory after it has been released. The guarantee comes from runtime checks, from a garbage collector, from a compiler that proves the rules (Rust's ownership model), or from a mix.

Property Memory-unsafe (C, C++) Memory-safe (Python, Java, Go, Rust)
Out-of-bounds access Allowed; undefined behavior Error or compile-time rejection
Use after free Possible Prevented by GC or ownership rules
Uninitialized memory Possible to read Initialized or rejected
Performance control Maximum Slightly less, or equal with Rust

"Undefined behavior" is the key term: the C standard does not say what happens, so the result may be a crash, silent data corruption, or code that runs because an attacker arranged the bytes.

Buffer overflows

A buffer is a fixed-size block, such as room for 8 characters of a username. A buffer overflow happens when more data is written than the buffer holds, so the extra bytes spill into whatever sits next to it. On the stack, neighbors can include other local variables and the saved return address, the place the function jumps to when it ends. If an attacker controls the spilled bytes, they can change what the program does next.

flowchart TB
    subgraph S["Stack frame (simplified, addresses grow downward)"]
        direction TB
        A["Return address<br/>(where to resume)"]
        B["Saved variables<br/>(for example is_admin flag)"]
        C["Buffer: 8 bytes<br/>(username)"]
    end
    IN["Input longer than 8 bytes"] -->|"writes upward past the buffer"| C
    C -.->|"spill"| B
    B -.->|"more spill"| A

An unchecked copy into the buffer overwrites its neighbors. Modern compilers add guards, but the bug itself remains.

This Python program simulates the memory as a bytearray so you can see the effect without any real danger. A "copy" function without a length check behaves like C's strcpy; the checked version rejects too-long input:

Python A simulated stack overflow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The real bug in C looks innocent: a char name[8] and a strcpy(name, input). The fixes are to use functions that take a length (snprintf, strlcpy, C++ std::string and std::vector), always check sizes before copying, and prefer containers that know their own length.

Use-after-free

C and C++ programmers release memory by hand (free, delete). A use-after-free bug occurs when the program keeps a pointer after the memory was freed and uses it again. In the meantime the allocator may have given that memory to something else, so the old pointer now reads or modifies unrelated data, possibly data an attacker influenced. A related bug is a double free, which corrupts the allocator's bookkeeping.

The simulation below uses a tiny allocator with numbered slots, to show why a stale handle is dangerous and how a safe design (a "generation" counter, an idea also used by some safe-language runtimes) detects it:

Python Stale pointers in a toy allocator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Memory-safe languages avoid this class of bug by design. Garbage-collected languages never free memory that something can still reach. Rust tracks ownership and lifetimes at compile time, so code that could use memory after it is freed is rejected by the compiler. This does not make programs bug-free, but the remaining bugs are logic mistakes, not silent corruption.

Choosing languages

For new projects that handle untrusted input (network services, parsers, file converters, browsers, operating-system components), a memory-safe language is the single most effective decision you can make. Government security agencies and major vendors now explicitly recommend it. Practical guidance:

  • New code: pick a memory-safe language unless there is a hard reason (hardware, real-time limits, an existing codebase).
  • Existing C/C++: rewrite the riskiest parts first, namely the code that parses untrusted data. Many teams add new components in Rust and keep the old core.
  • "Unsafe" escape hatches: Rust has unsafe blocks, Python has ctypes, Java has JNI. Keep them tiny, reviewed and isolated.
  • Safe languages still have flaws: injection, broken access control, weak crypto and logic bugs all remain; memory safety removes one category, not all.
  • Libraries count: a Python package written in C (for example an image decoder) can contain memory bugs. Keep native dependencies updated (Dependency and Supply Chain Security).

Hardening for code you cannot rewrite

When C or C++ remains, compilers and operating systems add layers that make exploitation harder. None of them fix the bug, but together they raise the cost of an attack:

Defense What it does
Stack canaries (-fstack-protector-strong) A secret value placed before the return address; if an overflow changes it, the program aborts before returning
ASLR The OS randomizes where code, stack and heap live, so attackers cannot rely on fixed addresses
Non-executable memory (NX/DEP) Data areas cannot run as code
PIE (-fPIE -pie) Makes the executable itself relocatable so ASLR covers it
Fortified libraries (-D_FORTIFY_SOURCE=2 or 3) Checks sizes in common functions like memcpy where the compiler knows them
RELRO (-Wl,-z,relro,-z,now) Makes dynamic-linking tables read-only after start
Control-flow integrity Restricts indirect jumps to valid targets

Alongside these, use sanitizers during testing (-fsanitize=address,undefined finds overflows, use-after-free and undefined behavior), run fuzzers on parsers (Security Code Review, SAST and Testing), and enable compiler warnings as errors. A hardened build is a safety net; it does not make an unsafe design acceptable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What defines a buffer overflow?

    An overflow is writing beyond the end of a fixed-size buffer so the extra bytes land in adjacent memory, such as other variables or a return address.
  2. 2. Which describes a use-after-free bug?

    After the free, the memory may be reused for something else, so the stale pointer accesses unrelated or attacker-influenced data.
  3. 3. Why does switching a new network service from C to a memory-safe language reduce risk?

    Memory-safe languages prevent those bug classes, though injection, access-control mistakes and logic errors still need defending.
  4. 4. What does ASLR do?

    Address space layout randomization changes where code, stack and heap are placed in each run, making fixed-address attacks unreliable.

Summary

  • Memory-safety bugs (overflows, use-after-free, out-of-bounds reads) let attackers corrupt or read memory and have caused many of the worst vulnerabilities.
  • Memory-safe languages prevent these bugs through checks, garbage collection or compile-time ownership rules; unsafe escape hatches should be small and reviewed.
  • For C and C++ you cannot rewrite, use bounded functions and safe containers, and build with stack protectors, ASLR/PIE, NX, fortify and RELRO.
  • Test with sanitizers and fuzzers, and prioritize replacing code that parses untrusted input.

Next: Dependency and Supply Chain Security, because the code you did not write is part of your attack surface too.