Programming Search⌘K

Weaknesscore

Out-of-bounds read

Also called OOB read, buffer over-read, buffer under-read, cwe-125.

An out-of-bounds read happens when a program reads memory past the end, or before the start, of a buffer, so it returns or uses bytes that belong to other data.

Abstraction
base
CWE Top 25 (2025)
rank 8
Languages affected
c, cpp, assembly, unsafe-code-in-any-language

Description

A buffer in C and C++ is a run of bytes at an address. A read through an index or a pointer returns whatever is at the computed address, and nothing checks that the address is inside the buffer. An out-of-bounds read happens when the program reads past the end of the buffer, or before its start.1 The read does not change memory and it does not crash in most cases. The program gets bytes that belong to something else, and it uses them, prints them or sends them back.

The root cause is a length or an index that the program does not compare with the real size of the buffer. Three forms are common. The first is a length that comes from input: a message says that its payload is 64 bytes long, and the code copies 64 bytes from a payload of 5. CWE-125 describes Heartbleed in these terms, an inconsistent length parameter that enables a buffer over-read.1 The second is a check that tests only one side of the range: if (index < len) with a signed index lets -1 through and reads before the buffer.1 The third is a sentinel that is not there: a string with no final '\0' makes strlen and printf read on until they find a zero byte somewhere in memory.1

This weakness is quick to make and hard to see. A write past the end often corrupts something and fails later. A read past the end usually returns plausible bytes and the program goes on. The tests send well-formed input, so the length and the buffer agree. The bug shows only when someone sends a length that does not match, and then the output contains data that the program never meant to send.

CWE-125 lists the consequences. An attacker can get secret values such as cryptographic keys and personal data. The bytes can hold memory addresses that help to defeat address space layout randomization when the attacker exploits a separate bug. A read that runs into unmapped memory crashes the program, and this is likely when the code relies on a sentinel.1

CWE-125 names this weakness. Its alternate term is OOB read. It is a base weakness under CWE-119, and its children are the buffer over-read, CWE-126, and the buffer under-read, CWE-127. It is often resultant: an earlier error, such as an Integer overflow or wraparound in a length, produces the bad index.1 It is rank 8 of the 2025 CWE Top 25, with 3 CVEs in the CISA catalogue of known exploited vulnerabilities, and it was rank 6 the year before.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 The write in the other direction is Out-of-bounds write.

History

RFC 6520, published in February 2012, defined the TLS and DTLS heartbeat extension. A heartbeat request carries a payload and a 16-bit payload_length, and the peer sends the payload back. The RFC says that a message with a payload_length that is too large must be discarded silently.4 The OpenSSL implementation did not do this check. On 2014-04-07, CVE-2014-0160 recorded that crafted heartbeat packets made OpenSSL 1.0.1 before 1.0.1g read past its buffer and return process memory, including private keys.6 The bug was named Heartbleed. It was found independently by Neel Mehta of Google Security and by a team of engineers at Codenomicon, while they improved a feature of their security testing tools.5

Vulnerable code

echo copies the number of bytes that the sender claims into a reply, as a heartbeat handler does. The program sends the classic demonstration input: a 5-byte payload with a claimed length of 64. The block builds with AddressSanitizer, which reports the read.7

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 the first claimed bytes of payload.
unsigned char *echo(const unsigned char *payload, size_t received, size_t claimed) {
    (void)received; // the real size is ignored
    unsigned char *reply = malloc(claimed);
    if (reply != NULL) {
        memcpy(reply, payload, claimed); // claimed comes from the sender
    }
    return reply;
}

int main(void) {
    size_t received = 5;
    unsigned char *payload = malloc(received);
    if (payload == NULL) {
        return 1;
    }
    memcpy(payload, "hello", received);
    unsigned char *reply = echo(payload, received, 64);
    if (reply != NULL) {
        printf("reply of 64 bytes starts with %.5s\n", (const char *)reply);
    }
    free(reply);
    free(payload);
}

AddressSanitizer stops the program with a heap-buffer-overflow report for a READ of size 64 in memcpy. Without the sanitizer, the program copies 59 bytes of whatever lies after the payload on the heap, and it exits with status 0. In a server, those bytes go back to the sender.

Fixed code

The fix compares the claimed length with the number of bytes that arrived, and it drops the message when they do not agree, as RFC 6520 requires.4 The block builds with AddressSanitizer and UndefinedBehaviorSanitizer, and both stay silent.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Returns a copy of the first claimed bytes of payload,
// or NULL when the payload is shorter than claimed.
unsigned char *echo(const unsigned char *payload, size_t received, size_t claimed) {
    if (claimed > received) {
        return NULL; // discard the message
    }
    unsigned char *reply = malloc(claimed > 0 ? claimed : 1);
    if (reply != NULL) {
        memcpy(reply, payload, claimed);
    }
    return reply;
}

int main(void) {
    size_t received = 5;
    unsigned char *payload = malloc(received);
    if (payload == NULL) {
        return 1;
    }
    memcpy(payload, "hello", received);
    size_t claims[] = {5, 64};
    for (size_t i = 0; i < 2; i++) {
        unsigned char *reply = echo(payload, received, claims[i]);
        if (reply == NULL) {
            printf("claimed %zu: discarded\n", claims[i]);
        } else {
            printf("claimed %zu: %.*s\n", claims[i], (int)claims[i], (const char *)reply);
            free(reply);
        }
    }
    free(payload);
}
Output
claimed 5: hello
claimed 64: discarded

The length that controls the copy must come from the buffer, not from the message. CWE-125 says to validate every length argument, buffer size calculation and offset, and to be careful with sentinels in untrusted input.1 For a signed index, check both ends: index >= 0 && index < len.1 The C example file shows the missing '\0'.

Languages that check reads

In Rust, Go, Java, C#, Python and JavaScript, a slice, an array or a string knows its length, and the runtime checks each index. The page Out-of-bounds write shows the check for single elements. A read of a range is different. Several languages do not report a range that is too long. They return less data or fill the gap, and the program goes on with a reply of the wrong size.

  • Python clamps a slice. If an end is greater than len(s), Python uses len(s).11 payload[:64] returns 5 bytes.
  • subarray of a JavaScript typed array clamps the range to the valid indices.12
  • Arrays.copyOfRange in Java accepts an end past the length of the array and fills the rest of the copy with zeros.10
  • A Go slice expression can go up to the capacity of the slice, not only to its length.8 When a program reuses a buffer, buf[:n] with n past the length returns old bytes from the earlier use. This is Heartbleed inside a memory-safe language.
  • Rust get with a range returns None when the range is out of bounds.9 A C# span over a range that does not fit throws ArgumentOutOfRangeException.13

Each example file shows the behavior and the explicit check. In every language, the fix is the same as in C: compare the claimed length with the real length, and reject the input when they differ.

How to detect it

  • Sanitizers. Build the tests with -fsanitize=address. AddressSanitizer detects out-of-bounds accesses to the heap, the stack and globals.7 CWE-125 rates it as moderately effective, because a test must reach the code with a bad length.1
  • Fuzzing. CWE-125 rates fuzzing as highly effective.1 A fuzzer sends lengths that do not match the data, and a sanitized build turns each over-read into a failure. Codenomicon found Heartbleed with its security testing tools.5
  • Static analysis. CWE-125 rates automated static analysis as highly effective.1 CodeQL query cpp/overflow-buffer finds calls such as memcpy whose size can be larger than the buffer that they read or write.15
  • Code review. For each copy and each loop over a buffer, find where the length comes from. A length from a header, a field of a message or a file is untrusted. Check signed indices at both ends. Check that each string from outside has a final '\0' before a string function reads it.

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-125 lists language selection as a mitigation.31
  • Take the length from the buffer. Copy min(claimed, received) bytes, or better, reject the input when they differ. Use types that carry their size, such as std::span in C++ and slices in Rust and Go.
  • Validate every length, offset and index. Check the minimum and the maximum, and check the arithmetic that computes a length for overflow.1
  • Do not trust sentinels in input. CWE-125 warns against relying on a sentinel such as NUL in untrusted input.1 On data from outside, use functions that take a maximum size, such as strnlen and memchr.
  • Clear memory that holds secrets, and do not hand out uninitialized memory. A read past the end returns what is next to the buffer. The Node.js documentation warns that Buffer.allocUnsafe returns memory that is not initialized and may contain sensitive data.14

Real cases

Case Date What happened
CVE-2014-0160 published 2014-04-07 Heartbleed. The TLS and DTLS heartbeat code of OpenSSL 1.0.1 before 1.0.1g read past its buffer and sent process memory, including private keys, to remote attackers.65
CVE-2020-11899 published 2020-06-17 The Treck TCP/IP stack before 6.0.1.66 had an out-of-bounds read in its IPv6 code. CWE-125 lists it as exploited in the wild.161
CVE-2023-1018 published 2023-02-28 The TPM 2.0 module library read 2 bytes past the end of a command in CryptParameterDecryption, which could expose data stored in the TPM.17
CVE-2018-10887 published 2018-07-10 An unexpected sign extension in git_delta_apply of libgit2 led to an integer overflow and then to a read before the base object, which could leak memory addresses.18
PythonGitHub

This code runs but gives a wrong answer on purpose.

def echo(payload, claimed):
    return payload[:claimed]


payload = b"hello"
reply = echo(payload, 64)
print("claimed 64, reply has", len(reply), "bytes:", reply)
Output
claimed 64, reply has 5 bytes: b'hello'

A slice end past the length is clamped to the length. No memory leaks, but the program does not notice that the message lied about its size.

def echo(payload, claimed):
    if not 0 <= claimed <= len(payload):
        raise ValueError(f"claimed {claimed} bytes, received {len(payload)}")
    return payload[:claimed]


payload = b"hello"
for claimed in [5, 64]:
    try:
        print(f"claimed {claimed}:", echo(payload, claimed))
    except ValueError as error:
        print("discarded:", error)
Output
claimed 5: b'hello'
discarded: claimed 64 bytes, received 5
  • Verdict: native. Indexing raises IndexError out of range, and slicing clamps the bounds. The interpreter never reads outside an object.
  • A negative bound counts from the end, so a negative length from input selects other bytes. Check the range explicitly.
  • C extensions, ctypes and memoryview over foreign memory have no such check.

This code has a memory error, on purpose, and the sanitizer reports it.

#include <cstddef>
#include <iostream>
#include <string_view>
#include <vector>

// Returns a view of the first claimed bytes of the payload.
std::string_view echo(const std::vector<char>& payload, std::size_t claimed) {
    return std::string_view(payload.data(), claimed);
}

int main() {
    std::vector<char> payload{'h', 'e', 'l', 'l', 'o'};
    std::cout << echo(payload, 64) << '\n';
}

The string_view constructor takes the length on trust. Printing the view reads 64 bytes from a vector of 5, and AddressSanitizer reports a heap-buffer-overflow.

#include <cstddef>
#include <iostream>
#include <optional>
#include <span>
#include <string_view>
#include <vector>

// Returns the first claimed bytes of the payload, or nothing.
std::optional<std::string_view> echo(std::span<const char> payload, std::size_t claimed) {
    if (claimed > payload.size()) {
        return std::nullopt;
    }
    auto part = payload.first(claimed);
    return std::string_view(part.data(), part.size());
}

int main() {
    std::vector<char> payload{'h', 'e', 'l', 'l', 'o'};
    for (std::size_t claimed : {5, 64}) {
        if (auto reply = echo(payload, claimed)) {
            std::cout << "claimed " << claimed << ": " << *reply << '\n';
        } else {
            std::cout << "claimed " << claimed << ": discarded\n";
        }
    }
}
Output
claimed 5: hello
claimed 64: discarded
  • Verdict: absent. Views and spans carry a size, but their constructors do not check it against the real data. std::span::first(n) has the precondition n <= size(), and in a build that is not hardened, a violation is undefined behavior.
  • Build the view from the container, which knows its size, and check every length from input against size() before you narrow the view.
  • std::vector::at and std::string::at check single indices and throw std::out_of_range.
JavaGitHub

This code runs but gives a wrong answer on purpose.

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Main {
    // Returns the first claimed bytes of the payload.
    static byte[] echo(byte[] payload, int claimed) {
        return Arrays.copyOfRange(payload, 0, claimed);
    }

    public static void main(String[] args) {
        byte[] payload = "hello".getBytes(StandardCharsets.US_ASCII);
        byte[] reply = echo(payload, 64);
        System.out.println("reply length: " + reply.length);
        System.out.println("byte 10: " + reply[10]);
    }
}
Output
reply length: 64
byte 10: 0

copyOfRange accepts an end past the length of the array and fills the rest with zeros. No memory leaks, but the reply claims 64 bytes and the program does not notice that the input was wrong.

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Main {
    // Returns the first claimed bytes of the payload.
    static byte[] echo(byte[] payload, int claimed) {
        if (claimed < 0 || claimed > payload.length) {
            throw new IllegalArgumentException("claimed " + claimed + " bytes, received " + payload.length);
        }
        return Arrays.copyOfRange(payload, 0, claimed);
    }

    public static void main(String[] args) {
        byte[] payload = "hello".getBytes(StandardCharsets.US_ASCII);
        for (int claimed : new int[] {5, 64}) {
            try {
                byte[] reply = echo(payload, claimed);
                System.out.println("claimed " + claimed + ": " + new String(reply, StandardCharsets.US_ASCII));
            } catch (IllegalArgumentException e) {
                System.out.println("discarded: " + e.getMessage());
            }
        }
    }
}
Output
claimed 5: hello
discarded: claimed 64 bytes, received 5
  • Verdict: native. Every array access is checked, and an index out of range throws ArrayIndexOutOfBoundsException.
  • Arrays.copyOfRange and Arrays.copyOf pad a copy that is longer than the source. Compare a length from input with length first.
  • 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 the first claimed bytes of payload.
unsigned char *echo(const unsigned char *payload, size_t received, size_t claimed) {
    (void)received; // the real size is ignored
    unsigned char *reply = malloc(claimed);
    if (reply != NULL) {
        memcpy(reply, payload, claimed); // claimed comes from the sender
    }
    return reply;
}

int main(void) {
    size_t received = 5;
    unsigned char *payload = malloc(received);
    if (payload == NULL) {
        return 1;
    }
    memcpy(payload, "hello", received);
    unsigned char *reply = echo(payload, received, 64);
    if (reply != NULL) {
        printf("reply of 64 bytes starts with %.5s\n", (const char *)reply);
    }
    free(reply);
    free(payload);
}

AddressSanitizer reports a heap-buffer-overflow for a READ of size 64. The payload has 5 bytes, and the copy reads 59 more.

This code has a memory error, on purpose, and the sanitizer reports it.

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

int main(void) {
    char name[5];
    memcpy(name, "alice", 5); // five letters, no room for '\0'
    printf("length: %zu\n", strlen(name));
}

strlen reads until it finds a zero byte. The array holds five letters and no '\0', so the read goes past the end of the array on the stack. AddressSanitizer reports a stack-buffer-overflow.

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[5];
    memcpy(name, "alice", 5);
    size_t length = strnlen(name, sizeof name);
    printf("length: %zu\n", length);
    printf("name: %.*s\n", (int)length, name);
}
Output
length: 5
name: alice
  • Verdict: absent. C does not check reads. A pointer carries no size, and an index is not compared with the length of the array.
  • Pass the size of each buffer with the buffer, and compare every length from input with it before a copy.
  • Use strnlen, memchr and %.*s on data that may lack a final '\0'.
  • Check a signed index at both ends. CWE-125 shows a check of index < len alone, which lets a negative index read before the buffer.

This code raises ArgumentOutOfRangeException, on purpose.

static ReadOnlySpan<byte> Echo(byte[] payload, int claimed) => payload.AsSpan(0, claimed);

byte[] payload = "hello"u8.ToArray();
Console.WriteLine(Echo(payload, 5).Length);
Console.WriteLine(Echo(payload, 64).Length);

AsSpan(0, 64) on an array of 5 bytes throws ArgumentOutOfRangeException, because the range is not inside the array.

using System.Text;

static bool TryEcho(byte[] payload, int claimed, out ReadOnlySpan<byte> reply)
{
    if (claimed < 0 || claimed > payload.Length)
    {
        reply = default;
        return false;
    }
    reply = payload.AsSpan(0, claimed);
    return true;
}

byte[] payload = "hello"u8.ToArray();
foreach (int claimed in new[] { 5, 64 })
{
    if (TryEcho(payload, claimed, out var reply))
    {
        Console.WriteLine($"claimed {claimed}: {Encoding.ASCII.GetString(reply)}");
    }
    else
    {
        Console.WriteLine($"claimed {claimed}: discarded");
    }
}
Output
claimed 5: hello
claimed 64: discarded
  • Verdict: native. Array, span and string accesses are checked, and a range out of bounds throws an exception.
  • An unhandled exception is a denial of service. Check lengths from input and return a result instead.
  • unsafe code with pointers, stackalloc and Unsafe methods can read out of bounds.
JavaScriptGitHub

This code runs but gives a wrong answer on purpose.

function echo(payload, claimed) {
  return payload.subarray(0, claimed);
}

const payload = new TextEncoder().encode("hello");
const reply = echo(payload, 64);
console.log(`claimed 64, reply has ${reply.length} bytes: ${new TextDecoder().decode(reply)}`);
Output
claimed 64, reply has 5 bytes: hello

subarray clamps the range to the array. The program does not notice that the claimed length was wrong.

function echo(payload, claimed) {
  if (!Number.isInteger(claimed) || claimed < 0 || claimed > payload.length) {
    throw new RangeError(`claimed ${claimed} bytes, received ${payload.length}`);
  }
  return payload.subarray(0, claimed);
}

const payload = new TextEncoder().encode("hello");
for (const claimed of [5, 64]) {
  try {
    console.log(`claimed ${claimed}: ${new TextDecoder().decode(echo(payload, claimed))}`);
  } catch (error) {
    console.log(`discarded: ${error.message}`);
  }
}
Output
claimed 5: hello
discarded: claimed 64 bytes, received 5
  • Verdict: native. A read out of range of an array gives undefined, and typed arrays read only their ArrayBuffer.
  • In Node.js, Buffer.allocUnsafe returns memory that is not initialized and may contain sensitive data. A reply built from such a buffer with a claimed length leaks old data, as Heartbleed did. Use Buffer.alloc.
  • Out-of-bounds reads in the engine and in native add-ons are outside the reach of script.

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

// echo returns the first claimed bytes of the payload.
func echo(payload []byte, claimed int) []byte {
	return payload[:claimed]
}

func main() {
	buf := make([]byte, 0, 32)
	buf = append(buf, "user=alice;pin=4321"...) // an earlier request
	buf = buf[:0]                                // reuse the buffer
	buf = append(buf, "hello"...)

	fmt.Printf("%q\n", echo(buf, 5))
	fmt.Printf("%q\n", echo(buf, 19))
}
Output
"hello"
"helloalice;pin=4321"

The slice has a length of 5 and a capacity of 32. The Go specification allows the upper bound of a slice expression to go up to the capacity, so buf[:19] does not panic. It returns the old bytes of the earlier request. A claimed length past the capacity panics.

package main

import (
	"errors"
	"fmt"
)

// echo returns the first claimed bytes of the payload.
func echo(payload []byte, claimed int) ([]byte, error) {
	if claimed < 0 || claimed > len(payload) {
		return nil, errors.New("the claimed length does not match the payload")
	}
	return payload[:claimed], nil
}

func main() {
	buf := make([]byte, 0, 32)
	buf = append(buf, "user=alice;pin=4321"...)
	buf = buf[:0]
	buf = append(buf, "hello"...)

	for _, claimed := range []int{5, 19} {
		reply, err := echo(buf, claimed)
		if err != nil {
			fmt.Printf("claimed %d: %v\n", claimed, err)
			continue
		}
		fmt.Printf("claimed %d: %q\n", claimed, reply)
	}
}
Output
claimed 5: "hello"
claimed 19: the claimed length does not match the payload
  • Verdict: native. Indices and slice expressions are checked at run time, and a bound past the capacity panics.
  • The check uses the capacity, not the length. Code that reuses buffers must compare a length from input with len, as the second example does.
  • The packages unsafe and cgo skip the checks.
RustGitHub

This code panics, on purpose.

fn echo(payload: &[u8], claimed: usize) -> &[u8] {
    &payload[..claimed]
}

fn main() {
    let payload = b"hello";
    println!("{:?}", echo(payload, 5));
    println!("{:?}", echo(payload, 64));
}

The range ..64 is past the end of a slice of 5 bytes. The program panics with range end index 64 out of range for slice of length 5, and no memory past the slice is read.

fn echo(payload: &[u8], claimed: usize) -> Option<&[u8]> {
    payload.get(..claimed)
}

fn main() {
    let payload = b"hello";
    for claimed in [5, 64] {
        match echo(payload, claimed) {
            Some(reply) => println!("claimed {claimed}: {}", String::from_utf8_lossy(reply)),
            None => println!("claimed {claimed}: discarded"),
        }
    }
}
Output
claimed 5: hello
claimed 64: discarded
  • Verdict: native. Every index and range on a slice is checked. A failed check panics, and get returns None instead.
  • A panic is still a denial of service. Use get for lengths and indices that come from input.
  • unsafe code with get_unchecked or raw pointers has no check, and it can read out of bounds as C does.

References

  1. CWE-125: Out-of-bounds Read, Description; Alternate Terms; Common Consequences; Potential Mitigations; Relationships; Demonstrative Examples, Example 1; Detection Methods; Observed Examples
  2. 2025 CWE Top 25 Most Dangerous Software Weaknesses, the ranked list, rank 8, CVEs in KEV, Rank Last Year
  3. OWASP Top 10:2025, Next Steps, X02:2025 Memory Management Failures, X02:2025, Description; How to prevent; List of Mapped CWEs
  4. RFC 6520, Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) Heartbeat Extension, February 2012, 4. Heartbeat Request and Response Messages
  5. The Heartbleed Bug, Codenomicon, the opening section; Who found the Heartbleed Bug?
  6. CVE-2014-0160, OpenSSL (Heartbleed), the description and the publication date
  7. Clang documentation, AddressSanitizer, Introduction; Usage
  8. The Go Programming Language Specification, Slice expressions, Simple slice expressions
  9. Rust standard library, slice, get
  10. Java SE 25 API, java.util.Arrays, copyOfRange
  11. The Python Standard Library, Built-in Types, Common Sequence Operations, note 4
  12. MDN Web Docs, TypedArray.prototype.subarray(), Description
  13. .NET API, MemoryExtensions.AsSpan Method, the overloads with start and length, Exceptions
  14. Node.js documentation, Buffer, Static method Buffer.allocUnsafe(size)
  15. CodeQL query help, Call to memory access function may overflow buffer (cpp/overflow-buffer), the query description; Recommendation
  16. CVE-2020-11899, Treck TCP/IP stack, the description and the publication date
  17. CVE-2023-1018, TPM 2.0 reference library, the description and the publication date
  18. CVE-2018-10887, libgit2, 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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4SWV9E/text.yaml