Weaknesscore
Out-of-bounds write
Also called buffer overflow, buffer overrun, memory corruption, cwe-787.
An out-of-bounds write happens when a program writes data past the end, or before the start, of a buffer, and so changes memory that belongs to other data or to the control flow of the program.
- CWE
- CWE-787
- Abstraction
- base
- CWE Top 25 (2025)
- rank 5
- Languages affected
- c, cpp, assembly, unsafe-code-in-any-language
Description
A buffer is a run of memory with a fixed size: an array, a string, a block from malloc. In C and C++, a write through an index or a pointer goes to the address that the program computed. Nothing checks that the address is inside the buffer. An out-of-bounds write happens when the program writes past the end of the buffer, or before its start.1 The bytes land in the memory next to it, which can hold other variables, the bookkeeping of the allocator or a return address. The program meant to store a name. It changed something else.
The root cause is that the size of a buffer and the code that writes to it are separate. The size is fixed when the buffer is made. The amount of data comes later, often from input. Every copy, every loop and every index must repeat the size check, and one missed check is enough. Common forms are a copy with no size limit, a size that does not count the final '\0' of a string, a loop that runs one step too far, and a size computed with an integer that wraps around.1
The consequences range from a crash to code execution. CWE-787 says that an attacker can sometimes change control data such as return addresses and run unexpected code.1 A write that changes only a nearby variable can still change the decisions of the program. When the bug does not crash, it is silent: the program goes on with corrupt memory.
CWE-787 names this weakness. Its alternate term is memory corruption. It is a base weakness under CWE-119, improper restriction of operations within the bounds of a memory buffer. Its children include the classic buffer overflow (CWE-120), the stack-based buffer overflow (CWE-121), the heap-based buffer overflow (CWE-122) and the buffer underwrite (CWE-124).1 CWE-787 lists C and C++ as languages where it is often prevalent.1 It is rank 5 of the 2025 CWE Top 25, with 12 CVEs in the CISA catalogue of known exploited vulnerabilities.2 The OWASP Top 10:2025 maps it to X02:2025 Memory Management Failures, a category in its Next Steps section and not in the ten.3
History
On the evening of 2 November 1988, a worm program spread through the Internet to thousands of machines that ran BSD-derived versions of UNIX.4 One of its attacks used the fingerd daemon. fingerd read one line of input with the C library function gets, which does no bounds check. The worm sent a string of 536 bytes into a buffer of 512 bytes, and on VAX computers the overflow changed the return address of main so that it pointed into the buffer.4 Spafford's paper, written fifteen years later, says that a whole family of routines in the C library can overrun buffers unless the programmer gives limits, and that hundreds of buffer overflow vulnerabilities had been found since.4 The paper names the author of the worm as Robert T. Morris.4
Vulnerable code
The function below copies a name to the heap. malloc(strlen(name)) leaves no room for the final '\0', and strcpy writes it one byte past the end. The block builds with AddressSanitizer, which reports the write.5
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of name on the heap.
char *copy_name(const char *name) {
char *copy = malloc(strlen(name)); // no room for the final '\0'
strcpy(copy, name);
return copy;
}
int main(void) {
char *name = copy_name("alice");
printf("%s\n", name);
free(name);
}
AddressSanitizer stops the program with a heap-buffer-overflow report for a WRITE of size 6 in strcpy. Without the sanitizer, the same program can print alice and exit with status 0. The bug is still there, and a longer name from input makes it larger. The C example file also shows a stack buffer that strcat overflows with the classic demonstration input, a long run of A.
Fixed code
The fix counts the '\0' in the size, and it copies exactly that size. The block builds with AddressSanitizer and UndefinedBehaviorSanitizer, and both stay silent.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of name on the heap, or NULL.
char *copy_name(const char *name) {
size_t size = strlen(name) + 1; // room for the final '\0'
char *copy = malloc(size);
if (copy != NULL) {
memcpy(copy, name, size);
}
return copy;
}
int main(void) {
char *name = copy_name("alice");
if (name == NULL) {
return 1;
}
printf("%s\n", name);
free(name);
}
alice
In C, each write needs a size that comes from the destination. snprintf takes the size of the destination and tells the program when the text did not fit. The C example file shows it. CWE-787 warns that strncpy may leave a string without the final '\0', so it is not a full replacement for strcpy.1
Languages that check the index
In most languages, an array or a string knows its length, and each index is checked at run time. The check turns the write into an error before any memory changes.
This code panics, on purpose.
fn set_score(scores: &mut [i32], player: usize, score: i32) {
scores[player] = score;
}
fn main() {
let mut scores = vec![0; 4];
set_score(&mut scores, 2, 10);
println!("player 2: {}", scores[2]);
set_score(&mut scores, 4, 99);
}
The Rust reference says that an index that fails the check puts the thread in a panicked state.8 Go panics at run time.9 Java throws ArrayIndexOutOfBoundsException, because all array accesses are checked.10 C# throws IndexOutOfRangeException.11 Python raises IndexError.12 A JavaScript typed array reads and writes only its ArrayBuffer, and the JavaScript example shows that a write past the end is dropped.13 Each example file shows the error and a fixed version that checks the index first.
In C++, std::vector::at throws std::out_of_range when the index is not less than size().6 operator[] has no such guarantee. The working draft of the standard lists n < a.size() as a hardened precondition of a[n]: a hardened implementation checks it and terminates, and in an implementation that is not hardened, a violation is undefined behavior.67
A panic or an exception is still a denial of service. It is not memory corruption, and it does not let an attacker change other data. The protection ends at unsafe code, raw pointers and native libraries. CWE-787 warns that the interface of a language to native code may still be subject to overflows.1
How to detect it
- Sanitizers. Build the tests with
-fsanitize=address. AddressSanitizer detects out-of-bounds accesses to the heap, the stack and globals, with a typical slowdown of two times.5 It finds a bug only when a test runs the line with a bad size. - Fuzzing. A fuzzer gives a sanitized build many generated inputs, so the tests reach sizes that a person did not think of. OWASP lists fuzzing of every input as a defence.3
- Static analysis. CodeQL queries
cpp/overrunning-write,cpp/unbounded-writeandcpp/badly-bounded-writefind copies and writes with no limit or with a wrong limit.141516 OWASP says to fix all compiler errors and warnings.3 - Code review. Search for
strcpy,strcat,sprintf,gets,memcpywith a computed size,malloc(strlen(...))without+ 1, and loops with<=. For each write, find where the size of the destination comes from.
How to prevent it
- Use a memory-safe language. OWASP puts a memory-safe language first among its defences against memory management failures, and CWE-787 lists language selection as its first mitigation.31 The Chromium project finds that around 70% of its high severity security bugs are memory unsafety problems.17
- Use types that carry their size. In C++, use
std::vector,std::string,std::arrayandstd::span, andatwhere the index comes from input. OWASP says to use managed buffers and strings rather than raw arrays and pointers.3 - Pass the size with every write. In C, use
snprintfand functions that take the size of the destination, check each index against the length, and count the final'\0'.114 - Check size arithmetic. A size that wraps around makes a small buffer, and every later write overflows it. CWE-787 lists this chain in its examples.1
- Harden the build. Compiler options such as
FORTIFY_SOURCEand stack canaries, and the address space layout randomization and non-executable memory of the operating system, make an overflow harder to exploit.1 CWE-787 says that none of these is a complete solution.1
Real cases
| Case | Date | What happened |
|---|---|---|
| Internet Worm | 1988-11-02 | The worm overflowed the 512-byte input buffer of fingerd with a 536-byte string, read by gets, and changed the return address on VAX systems.4 |
| CVE-2021-3156 | published 2021-01-26 | An off-by-one error in Sudo led to a heap-based buffer overflow and let a user become root through sudoedit -s and an argument that ends with a single backslash.18 |
| CVE-2020-0022 | published 2020-02-13 | An incorrect bounds calculation in reassemble_and_dispatch of the Android Bluetooth stack allowed an out-of-bounds write and remote code execution over Bluetooth with no user interaction.191 |
| CVE-2023-4863 | published 2023-09-12 | A heap buffer overflow in libwebp let a crafted HTML page write out of bounds in Google Chrome.20 |
This code raises IndexError, on purpose.
def set_score(scores, player, score):
scores[player] = score
scores = [0] * 4
set_score(scores, 2, 10)
print("player 2:", scores[2])
set_score(scores, 4, 99)
This code runs but gives a wrong answer on purpose.
def set_score(scores, player, score):
scores[player] = score
scores = [0] * 4
set_score(scores, -1, 99)
print(scores)
[0, 0, 0, 99]
A negative index is not an error in Python. It counts from the end, so player -1 changes the last score. Memory is safe, but the program wrote to the wrong element.
def set_score(scores, player, score):
if not 0 <= player < len(scores):
raise ValueError(f"player {player} is out of range, the size is {len(scores)}")
scores[player] = score
scores = [0] * 4
set_score(scores, 2, 10)
print("player 2:", scores[2])
for player in [4, -1]:
try:
set_score(scores, player, 99)
except ValueError as error:
print("refused:", error)
print(scores)
player 2: 10
refused: player 4 is out of range, the size is 4
refused: player -1 is out of range, the size is 4
[0, 0, 10, 0]
- Verdict: native. A list,
bytearrayorarrayraisesIndexErrorfor an index out of range, so a write cannot leave the object. - Check the range yourself when the index comes from input, because a negative index is valid.
- The weakness comes back in native code. A C extension and
ctypeswrite to memory that Python does not check.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <cstddef>
#include <print>
#include <vector>
void set_score(std::vector<int>& scores, std::size_t player, int score) {
scores[player] = score; // operator[] does not check the index
}
int main() {
std::vector<int> scores(4);
set_score(scores, 2, 10);
std::println("player 2: {}", scores[2]);
set_score(scores, 4, 99);
}
AddressSanitizer reports a heap-buffer-overflow and a WRITE of size 4 in set_score. The vector has four elements, and index 4 is one past the end.
#include <cstddef>
#include <print>
#include <stdexcept>
#include <vector>
void set_score(std::vector<int>& scores, std::size_t player, int score) {
scores.at(player) = score; // at() checks the index and throws
}
int main() {
std::vector<int> scores(4);
set_score(scores, 2, 10);
std::println("player 2: {}", scores[2]);
try {
set_score(scores, 4, 99);
} catch (const std::out_of_range&) {
std::println("refused: player 4 is out of range, the size is {}", scores.size());
}
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: library. The containers carry their size, and
atthrowsstd::out_of_rangewhen the index is not less thansize().operator[], iterators and raw pointers do not check. - The working draft of the C++ standard lists
n < a.size()as a hardened precondition ofa[n]. A hardened implementation checks it and ends the program when it fails. In an implementation that is not hardened, a violation is undefined behavior. - Prefer
std::vector,std::string,std::arrayandstd::spanto raw arrays, and range-basedforloops to index arithmetic. Each one keeps the size next to the data. - AddressSanitizer finds the bug only when a test runs the line with a bad index. Fuzzing gives the tests many inputs.
This code raises ArrayIndexOutOfBoundsException, on purpose.
public class Main {
static void setScore(int[] scores, int player, int score) {
scores[player] = score;
}
public static void main(String[] args) {
int[] scores = new int[4];
setScore(scores, 2, 10);
System.out.println("player 2: " + scores[2]);
setScore(scores, 4, 99);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4
at Main.setScore(Main.java:3)
at Main.main(Main.java:10)
public class Main {
static boolean setScore(int[] scores, int player, int score) {
if (player < 0 || player >= scores.length) {
return false;
}
scores[player] = score;
return true;
}
public static void main(String[] args) {
int[] scores = new int[4];
setScore(scores, 2, 10);
System.out.println("player 2: " + scores[2]);
if (!setScore(scores, 4, 99)) {
System.out.println("refused: player 4 is out of range, the size is " + scores.length);
}
}
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: native. The Java Language Specification says that all array accesses are checked at run time, and an index less than zero or not less than the length throws
ArrayIndexOutOfBoundsException. - The exception stops the write. An uncaught exception is a denial of service, so check an index that comes from input.
- Native code that the program calls through JNI has no such check.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of name on the heap.
char *copy_name(const char *name) {
char *copy = malloc(strlen(name)); // no room for the final '\0'
strcpy(copy, name);
return copy;
}
int main(void) {
char *name = copy_name("alice");
printf("%s\n", name);
free(name);
}
AddressSanitizer reports a heap-buffer-overflow and a WRITE of size 6 in strcpy. The buffer has five bytes, and strcpy writes the five letters and the final '\0'. Without the sanitizer, the program can print alice and exit with status 0, which hides the bug.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <string.h>
void greet(const char *name) {
char line[16];
strcpy(line, "hello, ");
strcat(line, name); // no check that name fits
puts(line);
}
int main(void) {
greet("bob");
greet("AAAAAAAAAAAAAAAAAAAAAAAA");
}
The second call uses the classic demonstration input, a long run of A. AddressSanitizer reports a stack-buffer-overflow in strcat. On the stack, the bytes after line can hold the return address of greet, which is why this form is dangerous.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of name on the heap, or NULL.
char *copy_name(const char *name) {
size_t size = strlen(name) + 1; // room for the final '\0'
char *copy = malloc(size);
if (copy != NULL) {
memcpy(copy, name, size);
}
return copy;
}
// Writes a greeting into line and reports if it did not fit.
void greet(const char *name) {
char line[16];
int n = snprintf(line, sizeof line, "hello, %s", name);
if (n < 0 || (size_t)n >= sizeof line) {
printf("refused: the name needs %d bytes, the buffer has %zu\n", n + 1, sizeof line);
return;
}
puts(line);
}
int main(void) {
char *name = copy_name("alice");
if (name == NULL) {
return 1;
}
printf("%s\n", name);
free(name);
greet("bob");
greet("AAAAAAAAAAAAAAAAAAAAAAAA");
}
alice
hello, bob
refused: the name needs 32 bytes, the buffer has 16
- Verdict: absent. C has no bounds check on arrays, pointers or the string functions. A write past the end is undefined behavior, and the program does not have to fail.
- The fix computes each size from the data, adds one byte for
'\0', and uses functions that take the size of the destination.snprintfnever writes more than its size argument, and its return value tells the program that the text did not fit. strncpyis not a full fix. CWE-787 warns that it may not end the string with'\0'when the source is as long as the destination.- Build tests with
-fsanitize=address. Build releases with the hardening of the compiler, such asFORTIFY_SOURCEand stack canaries. They detect some overflows at run time, and the program then exits.
This code raises IndexOutOfRangeException, on purpose.
static void SetScore(int[] scores, int player, int score)
{
scores[player] = score;
}
var scores = new int[4];
SetScore(scores, 2, 10);
Console.WriteLine($"player 2: {scores[2]}");
SetScore(scores, 4, 99);
static bool SetScore(Span<int> scores, int player, int score)
{
if ((uint)player >= (uint)scores.Length)
{
return false;
}
scores[player] = score;
return true;
}
var scores = new int[4];
SetScore(scores, 2, 10);
Console.WriteLine($"player 2: {scores[2]}");
if (!SetScore(scores, 4, 99))
{
Console.WriteLine($"refused: player 4 is out of range, the size is {scores.Length}");
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: native. The runtime checks each index into an array, and a bad index throws
IndexOutOfRangeException.Span<T>carries its length and checks too. - The cast to
uintmakes one comparison reject both a negative index and an index past the end. - CWE-787 says that C# typically provides overflow protection, but that the programmer can turn it off. An
unsafeblock with pointers,stackallocinto a pointer and native code through P/Invoke have no check.
This code runs but gives a wrong answer on purpose.
const scores = new Int32Array(4);
scores[2] = 10;
scores[4] = 99;
console.log(scores.length, scores[4], Array.from(scores));
const list = [0, 0, 0, 0];
list[6] = 99;
console.log(list.length, list);
4 undefined [ 0, 0, 10, 0 ]
7 [ 0, 0, 0, 0, <2 empty items>, 99 ]
Neither write corrupts memory. The typed array keeps its length and drops the write past the end without an error. The plain array grows to fit the index and fills the gap with empty slots. Both are silent, so a bug in the index stays hidden.
function setScore(scores, player, score) {
if (!Number.isInteger(player) || player < 0 || player >= scores.length) {
throw new RangeError(`player ${player} is out of range, the size is ${scores.length}`);
}
scores[player] = score;
}
const scores = new Int32Array(4);
setScore(scores, 2, 10);
console.log("player 2:", scores[2]);
try {
setScore(scores, 4, 99);
} catch (error) {
console.log("refused:", error.message);
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: native. The engine checks each index into a typed array against its
ArrayBuffer, so script cannot write outside the buffer. - The language does not report a bad index. Check it yourself, as the second example does.
- Out-of-bounds writes still happen below the script, in the engine and in native add-ons, which are written in C and C++. CVE-2023-4863, in the libwebp image library, let a crafted HTML page write out of bounds in Google Chrome.
This code panics, on purpose.
package main
import "fmt"
func setScore(scores []int, player, score int) {
scores[player] = score
}
func main() {
scores := make([]int, 4)
setScore(scores, 2, 10)
fmt.Println("player 2:", scores[2])
setScore(scores, 4, 99)
}
The language specification says that an index out of range at run time causes a run-time panic. The panic happens before the write.
package main
import "fmt"
func setScore(scores []int, player, score int) error {
if player < 0 || player >= len(scores) {
return fmt.Errorf("player %d is out of range, the size is %d", player, len(scores))
}
scores[player] = score
return nil
}
func main() {
scores := make([]int, 4)
setScore(scores, 2, 10)
fmt.Println("player 2:", scores[2])
if err := setScore(scores, 4, 99); err != nil {
fmt.Println("refused:", err)
}
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: native. Index and slice expressions are checked at run time.
- A panic stops the goroutine and, if nothing recovers it, the program. Check an index that comes from input and return an error.
- The packages
unsafeandcgocan skip the checks. Code that uses them needs the same review as C.
This code panics, on purpose.
fn set_score(scores: &mut [i32], player: usize, score: i32) {
scores[player] = score;
}
fn main() {
let mut scores = vec![0; 4];
set_score(&mut scores, 2, 10);
println!("player 2: {}", scores[2]);
set_score(&mut scores, 4, 99);
}
The index is checked at run time. The program stops with a panic before it writes, so no memory outside the vector changes.
fn set_score(scores: &mut [i32], player: usize, score: i32) -> Result<(), String> {
match scores.get_mut(player) {
Some(slot) => {
*slot = score;
Ok(())
}
None => Err(format!("player {player} is out of range, the size is {}", scores.len())),
}
}
fn main() {
let mut scores = vec![0; 4];
set_score(&mut scores, 2, 10).unwrap();
println!("player 2: {}", scores[2]);
if let Err(error) = set_score(&mut scores, 4, 99) {
println!("refused: {error}");
}
}
player 2: 10
refused: player 4 is out of range, the size is 4
- Verdict: native. Each index into an array, a slice or a
Vecis checked. A failed check is a panic, and the reference says that a constant index can be checked at compile time. - A panic is a denial of service, not memory corruption. Use
getandget_mutwhere the index comes from input, and handleNone. - Iterators such as
iter_mutandchunks_mutremove most index arithmetic. unsafecode can skip the check, for example withget_unchecked_mutor raw pointers. The weakness can come back there and in C code that the program calls through FFI.
References
- CWE-787: Out-of-bounds Write, Description; Alternate Terms; Common Consequences; Potential Mitigations; Relationships; Applicable Platforms; Observed Examples
- 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 5, CVEs in KEV
- OWASP Top 10:2025, Next Steps, X02:2025 Memory Management Failures, X02:2025, Description; How to prevent; List of Mapped CWEs
- Eugene H. Spafford, A Failure to Learn from the Past, ACSAC 2003, 1. Introduction; 3.1 fingerd and gets; the description of the attack via the finger daemon
- Clang documentation, AddressSanitizer, Introduction; How to build
- Working Draft, Programming Languages: C++, [sequence.reqmts], a[n]; a.at(n)
- Working Draft, Programming Languages: C++, [structure.specifications], Hardened preconditions
- The Rust Reference, Array and array index expressions, Array and slice indexing expressions
- The Go Programming Language Specification, Index expressions
- The Java Language Specification, Java SE 25 Edition, Chapter 10: Arrays, 10.4 Array Access
- .NET API, IndexOutOfRangeException Class, Remarks
- The Python Standard Library, Built-in Exceptions, Python 3.14, IndexError
- MDN Web Docs, TypedArray, Description; Examples, Property access
- CodeQL query help, Potentially overrunning write (cpp/overrunning-write), the query description; Recommendation
- CodeQL query help, Unbounded write (cpp/unbounded-write), the query description
- CodeQL query help, Badly bounded write (cpp/badly-bounded-write), the query description
- The Chromium Projects, Memory safety, the opening statistics
- CVE-2021-3156, Sudo, the description and the publication date
- CVE-2020-0022, Android Bluetooth, the description and the publication date
- CVE-2023-4863, libwebp, the description and the publication date
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag P5VTR9 Edit this page History Report an error Markdown