Home

Offbyone

Off-by-one error, commonly called an off-by-one bug, is a frequent programming flaw where a loop boundary or index targets one element too many or too few. It typically arises from confusion between inclusive and exclusive bounds or between zero-based and one-based indexing. The result is that code accesses an element outside the intended range, or misses the first or last element.

Causes and patterns include using <= where < is intended in loops, or using length as the last

Examples are common across languages. In C, for (i = 0; i <= n; i++) accesses n+1 elements,

Mitigation strategies include adopting half-open intervals (start inclusive, end exclusive), using language-provided iteration constructs, and writing

See also: zero-based indexing; inclusive-exclusive bounds; boundary testing.

valid
index
instead
of
length-1.
It
also
occurs
when
iterating
over
ranges,
slices,
or
arrays
with
incorrect
start
or
end
values,
or
when
counting
elements
starting
from
1
in
a
context
that
is
zero-based.
Language
features
such
as
range,
slices,
or
iterators
can
either
conceal
or
reveal
the
bug
depending
on
whether
bounds
are
inclusive
or
exclusive.
whereas
the
correct
form
is
i
<
n.
In
Python,
range(n+1)
yields
0
through
n,
which
can
be
unintended
if
the
goal
is
0
through
n-1.
Strings
and
arrays
are
also
susceptible,
especially
when
calculating
last
indices
as
length-1
but
looping
with
length.
explicit
boundary
tests.
Boundary
and
stress
tests,
careful
review
of
loop
conditions,
and
static
analysis
can
help
detect
off-by-one
errors.
Understanding
the
difference
between
inclusive
and
exclusive
bounds
and
keeping
indexing
consistent
are
key
to
avoiding
them.