off-by-one error

lore

programming

The classic error of counting one too many or one too few, especially at the boundaries of a loop or range.

Also called a fencepost error (ten posts hold nine panels, not ten), it is the bug that lives at < versus <=, or at the first and last element. It is so common it is practically a rite of passage, which is why boundary cases get their own tests.

The off-by-one error is the bug that lives at less-than versus less-than-or-equal, at the first index and the last, at the boundary rather than in the logic. It is also called a fencepost error, from the observation that ten fence posts hold nine panels, which is the same confusion in a form people find intuitive.

Its persistence is not carelessness, it is that boundaries are genuinely where the mental model is thinnest. The middle of a loop is easy to reason about because it is the same every time; the beginning and end are special cases that require holding a slightly different picture, and every conversion between zero-based and one-based counting is an opportunity to hold the wrong one.

The security dimension is why it matters beyond correctness. A buffer written one byte past its end is a classic memory corruption primitive, and a bounds check that uses the wrong comparison is a vulnerability rather than a nuisance. That is why the defences are structural rather than attentional: languages with bounds checking, iterators that make the boundary implicit, and tests written specifically for the empty case, the single element, and the exact limit.

Also known as: off by one, obo, fencepost error, fencepost

Sources

  • The Jargon File ("fencepost error")

All glossary entries