Programming Search⌘K

Conceptcore

Off-by-one errors

Also called off-by-one error, off by one, OBOE, OBOB, OB1, fencepost error, fence post error, picket fence error, half-open interval, inclusive bound, exclusive bound.

An off-by-one error is a count or an index that is one too high or one too low, often a loop that runs one pass too many or too few. Half-open ranges prevent many of them.

Applies to
core-languages

Idea

A fence 30 feet long with a post every 3 feet has 10 sections and 11 posts, not 10. Code makes the same mistake when it counts the items from index m to index n as n − m, or when a loop runs one pass too many because it tests i <= n and not i < n. Such a mistake is an off-by-one error: a number that is one more or one less than the right value.

# Fenceposts: a fence of 30 feet with a post every 3 feet.
length, gap = 30, 3
sections = length // gap
print("sections:", sections, "posts:", sections + 1)

# Items 3 to 7, both included: the count is 7 - 3 + 1, not 7 - 3.
items = list(range(3, 8))
print(items, "count:", len(items))

# Half-open ranges: the length is stop - start, and they join with no gap.
a = list(range(10))
print(len(range(2, 6)) == 6 - 2)
print(a[:4] + a[4:] == a)

# The classic bug: <= runs one pass too many and reads past the end.
scores = [70, 85, 90]
i = 0
try:
    while i <= len(scores):
        print("score", scores[i])
        i += 1
except IndexError as e:
    print("IndexError:", e)
Output
sections: 10 posts: 11
[3, 4, 5, 6, 7] count: 5
True
True
score 70
score 85
score 90
IndexError: list index out of range

The fence of 10 sections needs 11 posts. The range of items from 3 to 7 has 5 items, one more than 7 − 3. In a half-open range the count is the difference of the bounds, and two ranges that share a bound join with no gap and no overlap. The last loop tests i <= len(scores), so it tries a fourth pass, and Python stops it with an IndexError.

How it works

The definition. An off-by-one error "is a logic error that involves a number that differs from its intended value by 1"1. It "often occurs in computer programming when a loop iterates one time too many or too few, usually caused by the use of non-strict inequality (≤) as the terminating condition where strict inequality (<) should have been used, or vice versa"1. The other common cause is "confusion over zero-based numbering"1.

Fenceposts. "A fencepost error (occasionally called a telegraph pole, lamp-post, or picket fence error) is a specific type of off-by-one error"1. The rule is that "a fence with n sections will have n + 1 posts"1. The same rule holds for the gaps between items, the commas in a list, the edges between nodes in a path, and the years between two dates.

Inclusive bounds. A range with both ends included has one more element than the difference of its bounds. Wikipedia asks how many items lie from m to n, both included: "An intuitive answer may be n − m, but that is off by one, exhibiting a fencepost error; the correct answer is n − m + 1"1.

Half-open ranges as the fix. A half-open range includes its lower bound and excludes its upper bound. Wikipedia notes that for this reason "ranges in computing are often represented by half-open intervals"1. Dijkstra compared the four ways to write the numbers 2 to 12 and chose 2 ≤ i < 132. With this form, "the difference between the bounds as mentioned equals the length of the subsequence", and "two subsequences are adjacent means that the upper bound of the one equals the lower bound of the other"2. With subscripts from 0, a sequence of length N has "the nicer range 0 ≤ i < N"2.

Half-open ranges in the languages. Many standard ranges and slices are half-open.

  • In Python, "The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j"3, and the values of a range stop before stop: "r[i] = start + step*i where i >= 0 and r[i] < stop"3.
  • In Go, a[low : high] "constructs a substring or slice", and "The result has indices starting at 0 and length equal to high - low"4.
  • In Rust, "The range start..end contains all values with start <= x < end. It is empty if start >= end"5.
  • In Java, a substring "begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex"6.

Loops over collections. A loop that takes the elements of a collection has no bounds to get wrong. The Wikipedia article on loops notes that enumerations "avoid potential off-by-one errors"7.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CIdiom
C#Native
JavaScriptStandard library
TypeScriptStandard libraryTypeScript has the half-open slice and substring methods of JavaScript, and an index past the end gives undefined. The compiler option noUncheckedIndexedAccess adds undefined to the type of an indexed element. No example file exists.
GoNative
RustNative
KotlinNativeKotlin writes 1..10 for a range that includes the end and until or ..< for a range that excludes it, and the JVM checks each array index. No example file exists because kotlinc is not installed.
SQLIdiomBETWEEN includes both ends, so a query writes the half-open form with >= and <, for example on dates.
BashIdiomThe brace expansion {1..10} includes both ends, and ${s:offset:length} takes a length, not an end. Bash does not stop a read past the end of an array. No example file exists.
PowerShellIdiomThe range operator 1..10 includes both ends. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no loops or indexes.
CSSDoes not applyCSS has no loops. The selector :nth-child() counts from 1.
Regular expressionsDoes not applyA regular expression has no indexes. The quantifier {m,n} includes both counts.
Language Verdict Mechanism
Python native half-open range and slices; IndexError for an index past the end
JavaScript stdlib half-open slice and substring; an index past the end gives undefined and no error
TypeScript stdlib the methods of JavaScript; noUncheckedIndexedAccess adds undefined to the type of an indexed element
Java native bounds checks on arrays; half-open substring, subList and IntStream.range
Kotlin native .. includes the end; until and ..< exclude it; bounds checks
C# native bounds checks on arrays; the range a[1..3] excludes the end and ^1 is the last element
Go native half-open slice expressions; for i := range n; a run-time panic for an index out of range
Rust native a..b excludes the end and a..=b includes it; a panic for an index out of bounds; get returns None
C idiom no bounds checks; the convention for (i = 0; i < n; i++) and a pointer one past the end
C++ stdlib iterator ranges from begin() to end(), one past the last element; at() checks the index
Bash idiom {1..10} includes both ends; ${s:offset:length} takes a length
PowerShell idiom 1..10 includes both ends
SQL idiom BETWEEN includes both ends; >= a AND < b is the half-open form
Regex n/a no indexes; the quantifier {m,n} includes both counts
HTML n/a no loops or indexes
CSS n/a no loops; :nth-child() counts from 1

The languages differ in two ways: the form of their ranges and what happens at a bad index. Python, Go, Rust, Java and C# have half-open ranges in the language or in the standard library, and they stop a program that reads past the end. C has no checks, so an off-by-one index reads or writes the memory next to an array. Bash, PowerShell and SQL have inclusive ranges, so their counts need the extra 1.

The example files show these differences. Python counts fenceposts, uses half-open slices and catches an IndexError. JavaScript reads undefined past the end of an array and joins words with separators between them. Java uses substring and catches an ArrayIndexOutOfBoundsException. C# uses the ranges 1..3 and ^1. Go splits a slice into chunks with half-open slice expressions and recovers from an index panic. Rust compares 0..n with 0..=n and uses windows for neighbors. C copies a string into a buffer with room for the null character. C++ uses end() and std::views::iota.

PythonGitHub
# n items need n - 1 separators.
words = ["red", "green", "blue"]
out = ""
for w in words:
    out += w + ", "
print(repr(out))  # one separator too many
print(repr(", ".join(words)))

# Chunks with half-open slices: the stop of one is the start of the next.
data = list(range(1, 11))
size = 4
chunks = [data[i:i + size] for i in range(0, len(data), size)]
print(chunks)

# n items have n - 1 pairs of neighbors.
temps = [12, 15, 11, 18]
rises = [temps[i + 1] - temps[i] for i in range(len(temps) - 1)]
print(rises)
print([b - a for a, b in zip(temps, temps[1:])])

# The last index is len - 1. A negative index counts from the end.
print(temps[len(temps) - 1], temps[-1])
Output
'red, green, blue, '
'red, green, blue'
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]
[3, -4, 7]
[3, -4, 7]
18 18
  • Verdict: native. The loop that adds ", " after each word leaves one separator too many, and join puts separators only between the items. The slices data[i:i + size] are half-open, so each chunk starts where the last one stopped, and the last chunk is shorter. Four temperatures give three differences, so the loop stops at len(temps) - 1, and zip with temps[1:] gives the same pairs with no index.
#include <print>
#include <ranges>
#include <stdexcept>
#include <string>
#include <vector>

int main() {
    std::vector<int> v{10, 20, 30, 40};

    // end() is one past the last element; the range is [begin, end).
    std::println("size {} = end - begin {}", v.size(), v.end() - v.begin());
    for (auto it = v.begin(); it != v.end(); ++it)
        std::print("{}{}", it == v.begin() ? "" : " ", *it);
    std::println("");

    // iota(a, b) excludes b.
    for (int i : std::views::iota(1, 5))
        std::print("{}{}", i == 1 ? "" : " ", i);
    std::println("");

    // substr takes a start and a count, not an end.
    std::string s = "hamburger";
    std::println("{} {}", s.substr(4, 4), s.substr(4, 8 - 4));

    // at() checks the index; operator[] does not.
    try {
        std::println("{}", v.at(v.size()));
    } catch (const std::out_of_range&) {
        std::println("at({}) is out of range", v.size());
    }
    std::println("last: {}", v.back());
}
Output
size 4 = end - begin 4
10 20 30 40
1 2 3 4
urge urge
at(4) is out of range
last: 40
  • Verdict: stdlib. The iterator range of a container is half-open: end() points one past the last element, so a loop stops when the iterator equals it, and end() - begin() is the size. std::views::iota(1, 5) gives 1 to 4. substr takes a count, so the end index 8 becomes the count 8 - 4. at() throws std::out_of_range for the index 4, where v[4] is undefined behavior.
JavaGitHub
import java.util.List;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int[] scores = {70, 85, 90};
        int total = 0;
        try {
            for (int i = 0; i <= scores.length; i++) {
                total += scores[i];
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("caught: " + e.getMessage());
        }
        System.out.println("total before the error: " + total);

        // substring(begin, end) excludes end, so its length is end - begin.
        String s = "hamburger";
        String part = s.substring(4, 8);
        System.out.println(part + " " + part.length());

        // IntStream.range excludes the end, rangeClosed includes it.
        System.out.println(IntStream.range(1, 5).boxed().toList());
        System.out.println(IntStream.rangeClosed(1, 5).boxed().toList());

        // subList is half-open too.
        List<String> days = List.of("mon", "tue", "wed", "thu", "fri");
        System.out.println(days.subList(1, 3));
    }
}
Output
caught: Index 3 out of bounds for length 3
total before the error: 245
urge 4
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[tue, wed]
  • Verdict: native. The JVM checks each array index, so the fourth pass of the loop with <= throws an ArrayIndexOutOfBoundsException before it reads anything. substring(4, 8) has length 8 − 4. IntStream.range and subList exclude the end, and rangeClosed includes it, so the two names tell the reader which form is in use.
#include <stdio.h>
#include <string.h>

int main(void) {
    /* Fenceposts: 30 feet with a post every 3 feet. */
    int sections = 30 / 3;
    printf("posts: %d\n", sections + 1);

    /* "hello" needs 6 bytes: 5 letters and the null character. */
    const char *word = "hello";
    char buf[6];
    printf("strlen %zu, needs %zu\n", strlen(word), strlen(word) + 1);
    if (strlen(word) < sizeof buf) {
        memcpy(buf, word, strlen(word) + 1);
        printf("copied: %s\n", buf);
    }

    /* snprintf writes at most size - 1 characters and a null. */
    char small[4];
    int n = snprintf(small, sizeof small, "%s", word);
    printf("wanted %d, got \"%s\"\n", n, small);

    /* The half-open loop over an array: i < n, never i <= n. */
    int a[] = {3, 1, 4, 1, 5};
    size_t len = sizeof a / sizeof a[0];
    int sum = 0;
    for (size_t i = 0; i < len; i++)
        sum += a[i];
    printf("sum %d of %zu items, last a[%zu] = %d\n", sum, len, len - 1, a[len - 1]);
    return 0;
}
Output
posts: 11
strlen 5, needs 6
copied: hello
wanted 5, got "hel"
sum 14 of 5 items, last a[4] = 5
  • Verdict: idiom. C checks no index, so the loop i <= len would read a[5], past the end, with undefined behavior. The code uses i < len. A string of 5 letters needs a buffer of 6 bytes for the null character, which is the classic fencepost of C strings. snprintf writes at most size - 1 characters and the null, and it returns the length it wanted, so a caller can see the cut.
int[] a = { 10, 20, 30, 40, 50 };

// The range 1..3 takes the indexes 1 and 2.
Console.WriteLine(string.Join(",", a[1..3]));

// ^1 is the last element; ^0 is one past the end.
Console.WriteLine($"{a[^1]} {a[a.Length - 1]}");
Console.WriteLine(string.Join(",", a[2..^0]));

// The length of a range is end - start.
Range r = 1..4;
var (offset, length) = r.GetOffsetAndLength(a.Length);
Console.WriteLine($"offset {offset}, length {length}");

try
{
    Console.WriteLine(a[a.Length]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("index 5 is out of range");
}

// for with <= on a one-based count: 1 to 5 is five passes.
int passes = 0;
for (int i = 1; i <= 5; i++) passes++;
Console.WriteLine($"passes: {passes}");
Output
20,30
50 50
30,40,50
offset 1, length 3
index 5 is out of range
passes: 5
  • Verdict: native. A C# range start..end excludes end, so a[1..3] has two elements and GetOffsetAndLength gives the length 3 for 1..4. The index ^1 counts from the end and is the last element, so the code does not write a.Length - 1. The array access a[5] throws an IndexOutOfRangeException. A loop from 1 with <= is also correct, but the bounds and the test must match.
JavaScriptGitHub
const scores = [70, 85, 90];
let total = 0;
for (let i = 0; i <= scores.length; i++) {
  total += scores[i]; // the last pass adds undefined
}
console.log("total with <=:", total);

total = 0;
for (let i = 0; i < scores.length; i++) {
  total += scores[i];
}
console.log("total with <:", total);

// slice and substring exclude the end index.
const s = "hamburger";
console.log(s.slice(4, 8), s.substring(4, 8).length);
console.log(s.slice(0, 3) + s.slice(3) === s);

// The last element is at length - 1. at(-1) counts from the end.
console.log(scores[scores.length], scores[scores.length - 1], scores.at(-1));

// Separators go between the items.
console.log(["a", "b", "c"].join("-"));
Output
total with <=: NaN
total with <: 245
urge 4
true
undefined 90 90
a-b-c
  • Verdict: stdlib. JavaScript does not stop a read past the end of an array: scores[3] is undefined, and 245 + undefined is NaN, so the bug shows up only in the result. slice(4, 8) and substring(4, 8) take the characters at 4, 5, 6 and 7, and two slices that share the index 3 give the whole string back.
package main

import "fmt"

func at(s []int, i int) (v int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
		}
	}()
	return s[i], nil
}

func main() {
	data := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

	// Half-open slices: the high index of one chunk is the low of the next.
	for lo := 0; lo < len(data); lo += 4 {
		hi := min(lo+4, len(data))
		fmt.Println(lo, hi, data[lo:hi], "len", hi-lo)
	}

	// range over an integer gives 0 to n-1.
	var idx []int
	for i := range 3 {
		idx = append(idx, i)
	}
	fmt.Println(idx)

	// An index of len(s) is out of range, and Go panics.
	_, err := at(data, len(data))
	fmt.Println(err)
}
Output
0 4 [1 2 3 4] len 4
4 8 [5 6 7 8] len 4
8 10 [9 10] len 2
[0 1 2]
runtime error: index out of range [10] with length 10
  • Verdict: native. The slice data[lo:hi] has the length hi - lo, and the chunks join with no gap because each hi is the next lo. The built-in min keeps the last hi at len(data). range 3 gives 0, 1 and 2. The index len(data) is one past the end, so Go panics, and the function turns the panic into an error with recover.
RustGitHub
fn main() {
    // 0..n excludes n, 0..=n includes it.
    let a: Vec<u32> = (0..5).collect();
    let b: Vec<u32> = (0..=5).collect();
    println!("{:?} len {}", a, a.len());
    println!("{:?} len {}", b, b.len());

    // The length of start..end is end - start.
    let r = 3..8;
    println!("{} {}", r.len(), r.end - r.start);

    // get returns None past the end; indexing would panic.
    let v = vec![10, 20, 30];
    println!("{:?} {:?}", v.get(2), v.get(3));
    println!("{:?}", v.last());

    // n elements have n - 1 windows of two.
    let temps = [12, 15, 11, 18];
    let rises: Vec<i32> = temps.windows(2).map(|w| w[1] - w[0]).collect();
    println!("{:?}", rises);

    // A slice of a slice is half-open too.
    let s = "hamburger";
    println!("{}", &s[4..8]);
}
Output
[0, 1, 2, 3, 4] len 5
[0, 1, 2, 3, 4, 5] len 6
5 5
Some(30) None
Some(30)
[3, -4, 7]
urge
  • Verdict: native. Rust has both forms in the syntax: 0..5 has five values and 0..=5 has six, so the reader sees the choice. v.get(3) returns None, where v[3] would panic with an index-out-of-bounds message. windows(2) gives the three pairs of neighbors of four values, with no index arithmetic.
  • Zero-based and one-based numbering. "Numbering from 0 is most common, but some languages start array numbering with 1"1, and in FORTRAN "subscripts always start at 1"2. Code that moves between them must add or remove 1 in the right places.
  • Buffer overflows. In C, a loop with <= writes one element past the end of an array. Wikipedia describes a common case: strncat writes "a terminating null character one byte beyond the maximum length specified"1. See out-of-bounds write.
  • Separators. A list of n items has n − 1 separators, so code that adds a comma after each item has one comma too many. join functions handle this.
  • Neighbors. A list of n items has n − 1 pairs of neighbors, so a loop that compares a[i] with a[i + 1] must stop one step earlier.
  • Ranges. See range and slice for the range and slice types of the languages.

Pitfalls

  • <= with a zero-based index. for (i = 0; i <= n; i++) runs n + 1 times. Use i < n.
  • The last element. The last index of a list of length n is n − 1, not n.
  • Inclusive library ranges. Some functions take an inclusive end or a count, not an exclusive end. Wikipedia gives the example of MATLAB, where linspace(0,10,5) gives five values, not five steps1. Read the documentation of each function.
  • Loops with do-while. Wikipedia notes that an off-by-one error "can occur if a do-while loop is used in place of a while loop (or vice versa)"1, because a do-while loop runs at least once.
  • Counts from dates and times. The days from Monday to Friday, both included, are 5, not 4. Wikipedia notes that the Julian calendar first had a leap year every three years, "due to counting inclusively rather than exclusively"1.

Cost

An off-by-one error costs nothing at run time and much at debug time. In languages with bounds checks, the error usually stops the program with a clear message at the bad index. In C and C++, a read past the end gives garbage and a write past the end damages other data, and Wikipedia notes that such a write "can cause an exploitable condition where an attacker can hijack the local variables for the calling routine"1. Tests at the boundaries, with an empty list, a list of one element and the last element, check the cases where these errors happen.

History

Wikipedia notes that "An early description of this error appears in the works of Vitruvius"1. In 1982 Dijkstra wrote EWD 831 in favor of half-open ranges and subscripts from 0. He reported the experience with the language Mesa, which had all four forms of intervals: "the use of the other three conventions has been a constant source of clumsiness and mistakes"2. He also noted that "in ALGOL 60 and in PASCAL, convention c) has been adopted"2, where convention c) includes both bounds. The slices of Python and Go and the ranges of Rust use the half-open form.

References

  1. Off-by-one error, Wikipedia, Introduction; Fencepost error; Looping over arrays; Security implications
  2. Edsger W. Dijkstra, Why numbering should start at zero (EWD 831), 1982, the whole note
  3. Built-in Types, The Python Standard Library, Common Sequence Operations, notes 3 and 4; Ranges
  4. The Go Programming Language Specification, Slice expressions
  5. Struct Range, The Rust Standard Library, Introduction
  6. String (Java SE 25 and JDK 25), substring(int beginIndex, int endIndex)
  7. Loop (statement), Wikipedia, Enumeration

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/6PMFVG/text.yaml