Skip to content
systemcoding.dev
Security

Stack Buffer Overflows Explained and How to Prevent Them

A stack buffer overflow writes past a local array into the data next to it. See how it happens in C, what a canary does, and which habits prevent it.

6 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the C, Rust and OpenSSL logos.

A stack buffer overflow happens when a C program copies more bytes into a local array than the array holds, and the extra bytes land on whatever the compiler placed next to it: other locals, the saved frame pointer, or the return address. Nothing in the language stops the copy. The program keeps running with a corrupted stack until the function returns, and that is where the damage shows. This post builds the smallest overflow, shows the stack layout it corrupts, and lists the habits and compiler switches that stop it. Examples target GCC 15 on x86-64 Linux 6.12 with glibc 2.41.

What the stack looks like

Each function call gets a stack frame. On x86-64 System V, the caller's call instruction pushes the return address, and the callee usually pushes the old frame pointer and then reserves space for its locals. The stack grows toward lower addresses, but an array is filled toward higher addresses. So a write that runs past the end of a local array climbs toward the saved frame pointer and the return address.

Higher addressesContents
topreturn address (where ret jumps)
nextsaved frame pointer
nextcanary, if -fstack-protector put one here
lowerlocal array, filled upward
lowestother locals and spill slots

The exact order is the compiler's choice. GCC places arrays above scalar locals when the stack protector is on, so that an overflowing array hits the canary before it hits a pointer variable. At -O0 without protection the layout is the textbook one, which is why tutorials use it.

The smallest overflow

This program copies its first argument into an eight-byte array with strcpy, which copies until it finds a NUL byte and never asks how big the destination is.

greet.cc
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    char name[8];

    if (argc < 2)
        return 1;
    strcpy(name, argv[1]);
    printf("hello %s\n", name);
    return 0;
}

Build it with the protections switched off, to see the bug without a safety net, and give it 24 characters:

Text
gcc -std=c17 -O0 -fno-stack-protector -D_FORTIFY_SOURCE=0 -o greet greet.c
./greet AAAAAAAAAAAAAAAAAAAAAAAA

The result is not defined by C. On a typical build the printf line appears, and then main returns into a smashed stack and the process dies with a segmentation fault:

Text
hello AAAAAAAAAAAAAAAAAAAAAAAA
Segmentation fault

The printf works because the overflow has not yet been used. The 24 A bytes plus the terminator overwrote the saved frame pointer and the return address with 0x4141414141414141, which is not a valid code address. When ret pops it, the CPU tries to fetch an instruction from there and the kernel delivers SIGSEGV. An attacker who controls those bytes controls where ret goes, which is the whole reason this bug class matters.

How the same program fails with a canary

Rebuild with the stack protector, still without fortification:

Text
gcc -std=c17 -O0 -fstack-protector-strong -D_FORTIFY_SOURCE=0 -o greet greet.c
./greet AAAAAAAAAAAAAAAAAAAAAAAA
Text
hello AAAAAAAAAAAAAAAAAAAAAAAA
*** stack smashing detected ***: terminated
Aborted (core dumped)

The compiler stored a random value, the canary, between the array and the saved registers, and checks it before ret. The overflow changed it, the check called __stack_chk_fail, and glibc printed the message and aborted the process. The shell's "Aborted" wording varies by shell. The program still did the wrong thing, but it died before the attacker's value reached ret. A canary turns a hijack into a crash. It does not fix the bug, and it does not catch an overflow that skips over the canary or that overwrites another local.

The overflow with fortification on

With Ubuntu or Fedora default flags, -O2 and _FORTIFY_SOURCE are both on. GCC then knows that name is eight bytes and replaces strcpy with __strcpy_chk, which compares the length at run time:

Text
gcc -std=c17 -O2 -D_FORTIFY_SOURCE=3 -o greet greet.c
./greet AAAAAAAAAAAAAAAAAAAAAAAA
Text
*** buffer overflow detected ***: terminated
Aborted (core dumped)

This one fires before printf runs, because the check sits on the copy itself and not at function exit. GCC can also warn at compile time when it sees the sizes, as -Wstringop-overflow does for constant sources. Later posts in this subcluster cover the compiler flags in detail; here the point is that the best defense is to catch the copy where it happens.

Why C allows it

C arrays decay to pointers when passed to a function, and a pointer carries no length. strcpy(dst, src) receives two addresses and nothing else, so it cannot know the capacity of dst. The same holds for gets (removed from the language in C11), sprintf, strcat, scanf("%s") and a memcpy whose length came from outside. All of them trust the caller, and the caller is often wrong in a corner case.

Habits that prevent it

  1. Pass the destination size and use functions that honor it. Use snprintf(dst, sizeof dst, "%s", src) instead of strcpy or sprintf, and check whether the return value is at least sizeof dst, which means truncation.

  2. Never use gets. Use fgets(buf, sizeof buf, stdin), and strip the newline yourself.

  3. Never use the width-less %s in scanf. Write %7s for an eight-byte buffer, one less than the size for the terminator.

  4. Compute lengths in size_t and validate them before a memcpy. A length read from a file or a socket is attacker input.

  5. Keep arrays small and local only for data whose maximum size you control. For input of unknown size, allocate on the heap after checking the size, and free it.

  6. Prefer sizeof dst over a repeated literal like 8, so the size follows the declaration when someone changes it.

Here is the corrected program with snprintf and a truncation check:

greet_safe.cc
#include <stdio.h>

int main(int argc, char **argv)
{
    char name[8];

    if (argc < 2)
        return 1;
    int n = snprintf(name, sizeof name, "%s", argv[1]);
    if (n < 0 || (size_t)n >= sizeof name) {
        fputs("name too long\n", stderr);
        return 2;
    }
    printf("hello %s\n", name);
    return 0;
}
Text
./greet_safe Alex
hello Alex
./greet_safe AAAAAAAAAAAAAAAAAAAAAAAA
name too long

snprintf always writes the terminator when the size is above zero, and returns the length it would have produced, so a return value of eight or more means the text did not fit. Truncating silently is its own bug, because a cut-off value can pass a later comparison it should have failed, so the check above rejects instead.

Defense in depth

No single switch is enough, so builds stack several. Build with -fstack-protector-strong so the canary exists, -D_FORTIFY_SOURCE=3 with optimization so library copies are checked, -Wall -Wextra -Wformat=2 so the compiler flags what it can, and run tests under AddressSanitizer with -fsanitize=address, which reports a stack overflow with the offending line and the variable name. The platform adds ASLR and non-executable stacks, which make a successful exploit harder after the overflow has happened. These are mitigations, not repairs. The repair is the bounded copy.

Taggedcbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.