Security operations

What Is a Buffer Overflow? How It Works, Types and Prevention

A buffer overflow is a memory bug that can crash a program or let an attacker run code. Here is how it works and how developers prevent it.

Cysoro Security TeamPublished · 7 min read
char buf[100]; gets(buf); // unsafe BUFFER: 100 bytes INPUT: 536 bytes — OVERFLOW Return address overwritten Fix: check the length first SECURITY OPERATIONS Bufferoverflow Too much data. The wrong memory.
Quick answer

A buffer overflow is a software flaw in which a program writes more data into a fixed-size memory buffer than the buffer can hold, so the excess overwrites adjacent memory. That can corrupt data, crash the program, or let an attacker overwrite control data and execute malicious code.

Key takeaways

  • A buffer overflow happens when unchecked input writes past the end of a fixed-size memory buffer.
  • Stack overflows can overwrite a return address and redirect execution; heap overflows corrupt dynamically allocated data.
  • Prevention starts with safe languages and bounds-checked functions, plus compiler and operating system protections and testing.

A buffer overflow is one of the oldest and best-known software flaws, and it is still dangerous. A program that trusts input without checking its size can be made to write past the end of its memory — and an attacker who controls that input can turn a crash into code execution.

What is a buffer overflow?

A buffer overflow is a condition in which a program tries to put more data into a buffer than the buffer can hold, or writes data into memory past the end of a buffer. A buffer is a sequential section of memory set aside to hold something, such as a string or an array.

OWASP describes it this way: writing outside the bounds of allocated memory can corrupt data, crash the program or cause the execution of malicious code, in its Buffer Overflow reference. The flaw is classified in MITRE's weakness catalogue as CWE-120, a buffer copy without checking the size of the input, and related weaknesses cover reads and writes past the end of a buffer.

The root cause is usually a broken assumption. The programmer assumes input will always be a certain size, or that a length value can be trusted, and the code does not check. When that assumption fails, data spills into memory that belongs to something else.

How does a buffer overflow attack work?

In a classic attack, the attacker sends data to a program, which stores it in an undersized stack buffer. The excess overwrites information on the call stack, including the function's return address, so that when the function returns, control passes to code the attacker supplied.

Think of a row of boxes on a shelf. Each box holds one piece of data. If you keep putting items into the first box after it is full, they spill into the next boxes and replace what was there. In memory, the "next boxes" can include the address the program should return to, or a pointer it will use next.

Modern systems make this harder with protections such as stack canaries, non-executable memory and address randomization. Attackers have responded with techniques such as return-oriented programming, which chains together short pieces of existing code instead of injecting new code.

What a stack buffer overflow overwrites Normal stackReturn addressSaved frame pointerBuffer: 100 bytesFunction returns normally After overflowReturn address overwrittenFrame pointer overwrittenBuffer + attacker dataFunction returns to attacker code The overflow does not just corrupt data: it can hijack control flow.
A stack overflow can replace the return address with an address the attacker chooses. Illustration by Cysoro.

What are the main types of buffer overflow?

The main types are stack-based, heap-based and off-by-one overflows. They differ in where the buffer lives and how much data spills past it, but all come from missing or wrong bounds checks.

TypeWhere it happensTypical impact
Stack-basedA buffer on the call stackOverwrites return address; can lead to code execution
Heap-basedDynamically allocated memoryCorrupts nearby heap data and pointers; can lead to code execution
Off-by-oneOne byte past the end of a bufferOften crashes or corrupts a single byte; sometimes exploitable
Integer overflow leading to overflowA size calculation wraps aroundA small allocation receives a large copy
Format stringUntrusted input used as a format stringRelated flaw; can read or write memory

Heap overflows are harder to exploit than stack overflows in the classic sense, because there is no return address sitting next to the buffer. They are still serious: corrupting heap metadata or function pointers can give an attacker control, and the most likely outcome without careful exploitation is a crash.

What code causes a buffer overflow?

Buffer overflows typically occur in code that relies on external data, depends on properties enforced outside the code, or is so complex that the programmer cannot predict its behaviour. Unsafe C and C++ functions are the most common trigger.

The classic example uses gets(), which reads input with no way to limit its length. A buffer declared as char buf[100]; followed by gets(buf); will overflow as soon as the user types more than 100 characters. Modern compilers warn against gets(), and it was removed from the C standard.

Other risky patterns include strcpy() without a length check, memcpy() with a length taken from user input, and strncpy() used incorrectly. Even bounded functions can cause a flaw when the bound is wrong, or when the programmer confuses bytes with characters, as in the OWASP example where a Unicode conversion writes twice as many bytes as the buffer holds.

What are real buffer overflow cases?

The best-known case is the Morris worm of November 1988. It exploited a buffer overflow in fingerd, the service that answered queries about logged-in users, by sending a 536-byte string into a 512-byte stack buffer that was filled with gets().

The overflow overwrote the return address and ran code that opened a shell, letting the worm spread to the next machine. About 6,000 machines were affected, roughly a tenth of the internet at the time, and the worm's author became the first person prosecuted under the US Computer Fraud and Abuse Act.

Buffer overflows have also appeared in widely used server products and libraries, including image and audio decoders. OWASP notes that flaws in a popular server product can become widely known and pose a significant risk, because many sites run the same code. That is why patching matters as much as writing safe code: check your site's headers and TLS with the free security headers checker.

What damage can a buffer overflow cause?

A buffer overflow can crash a program, corrupt data, or let an attacker execute arbitrary code. OWASP rates the severity as very high and the likelihood of exploit as high to very high.

  • Availability: the program crashes or enters an infinite loop, taking a service down.
  • Arbitrary code execution: the attacker runs code with the program's privileges, which can mean full control of the machine.
  • Data corruption: overwritten memory changes values, pointers or stored data in ways that are hard to predict.
  • Privilege escalation: a flaw in a privileged service can turn a low-privilege attacker into an administrator.

Even when exploitation fails, a crash is a denial of service. A service that restarts on every oversized request is effectively down for as long as the attacker keeps sending requests.

Which languages are vulnerable to buffer overflows?

Languages such as C, C++, Fortran and assembly are vulnerable, because they let the programmer manage memory directly and do not check every access. Java and Python are largely immune for application code, because they check array bounds, although overflows can still occur in the interpreter or in native libraries.

That distinction shapes how teams prevent the flaw. In C and C++, prevention is a discipline: every copy, read and write must be checked. In a memory-safe language, the language does that work, and the main risk moves to the unsafe code the language calls underneath.

Choosing a memory-safe language for new code is the strongest single step. CISA's Secure by Design guidance encourages manufacturers to use memory-safe languages and to treat memory safety as a product requirement, not a developer preference. Access control matters here too: a process that can only read what it needs, as in mandatory access control, limits what a memory flaw can reach.

How do you prevent buffer overflows?

Prevent buffer overflows at several levels: choose safe languages and libraries, check every length, enable compiler and operating system protections, and test with fuzzing. No single layer is enough on its own.

Four layers that prevent buffer overflows 1Memory-safe languages and librariesbounds-checked code by default, safe string and container types 2Validate and check every lengthnever trust input size; use bounded functions correctly 3Compiler and OS protectionsstack canaries, non-executable memory, address randomization 4Test and patchfuzzing, static analysis, and prompt patching of libraries
Defense in depth for memory safety: language, code, compiler and testing. Illustration by Cysoro.
  • Use safe functions. Replace gets() and unchecked strcpy() with bounded alternatives, and check that the bound is correct.
  • Validate input length. Reject or truncate input that is larger than the buffer before copying it.
  • Enable compiler protections. Stack canaries detect an overwritten return address, and non-executable stack memory stops injected code from running directly.
  • Use address randomization. Address space layout randomization makes it harder for an attacker to guess where code lives.
  • Fuzz your code. Feed random and oversized inputs to parsers and network handlers and watch for crashes.
  • Patch promptly. Keep servers, libraries and dependencies up to date, because a flaw in a shared library affects every program that uses it.

How do you detect a buffer overflow?

Detect buffer overflows by reviewing code that handles user input, running static analysis, fuzzing, and watching for crashes in testing and production. OWASP's testing guide covers testing for buffer overflows, and its code review guide covers reviewing code for them.

For server products and libraries, keep up with bug reports and apply patches. For custom code, review every place that accepts input through a request, a file or a network socket, and confirm it can handle arbitrarily large input safely.

Crashes are a signal, not just an annoyance. A crash that follows a specific input is worth investigating as a possible memory flaw, even if it looks like a simple bug. Log the input size and the code path, and reproduce it in a test environment before you dismiss it.

The bottom line

A buffer overflow is a simple flaw with serious consequences: a program writes more data than its buffer can hold, and the excess overwrites memory that controls what the program does next. The Morris worm showed in 1988 how far that can go.

The fix is also simple in principle: do not trust input size, use memory-safe languages and checked functions, turn on compiler protections, and test with fuzzing. Check that your own site is patched and correctly configured with the free SSL checker, and treat every crash on oversized input as a warning worth chasing.

Frequently asked questions

What is a buffer overflow in simple terms?

Think of pouring water into a small cup: if you pour more than it holds, the extra spills over. In a program, extra data spills past the end of a memory buffer and overwrites nearby memory.

What causes a buffer overflow?

The usual cause is code that copies or reads input without checking its size, often with unsafe C functions such as gets or strcpy, or with a wrong length passed to a copy function.

What is the difference between a stack and heap buffer overflow?

A stack overflow writes past a buffer on the call stack, where return addresses live, so it can redirect execution. A heap overflow writes past a buffer in dynamically allocated memory, corrupting nearby data structures.

Can buffer overflows happen in Python or Java?

Programs written in Python or Java are largely immune, because those languages check array bounds for you. Overflows can still occur in the interpreter itself or in native libraries those programs call.

What is a famous buffer overflow attack?

The Morris worm of 1988 used a buffer overflow in the fingerd service, sending a 536-byte string into a 512-byte buffer to run code on infected machines. About 6,000 machines were affected.

How do you prevent buffer overflows?

Use a memory-safe language where possible, use bounds-checked functions, validate input length, enable compiler protections such as stack canaries, and test with fuzzing and static analysis.

Is a buffer overflow the same as a stack overflow?

No. A stack buffer overflow is one type of buffer overflow. Stack overflow can also mean a program recursed so deeply that it ran out of stack space, which is a different problem.

Sources

  1. OWASP — Buffer Overflow
  2. OWASP — Buffer Overflow Cheat Sheet
  3. MITRE CWE-120 — Buffer Copy without Checking Size of Input
  4. CISA — Secure by Design guidance
  5. F5 — What is a Buffer Overflow attack?
Written & fact-checked byCysoro Security Team

The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against the OWASP Buffer Overflow reference, MITRE CWE-120 and the OWASP Buffer Overflow Cheat Sheet.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free