Off-by-One Errors in Loops

An off-by-one error usually changes the first or last position reached, which makes short traces especially useful.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. List the intended positions
  2. Check small lengths
  3. Write the intended visited indices before the loop
  4. Test the empty input and the smallest meaningful case

List the intended positions

A five-item list has valid offsets 0 through 4. Visiting offsets below five reaches all items. Visiting offsets at most five adds an invalid access. Zero-based indexing tells you why the length is a stopping point.

Check small lengths

At length one, a loop starting at offset 1 and stopping below the length executes zero times. At length zero, accessing the first element before the loop fails even if the bounds are otherwise correct. Use boundary cases for zero, one, and two items.[1]

Write the intended visited indices before the loop

An array with values A, B, and C uses indices 0, 1, and 2. Starting at 1 skips A. Stopping at a condition allowing 3 attempts one index beyond the array. For a slice of adjacent pairs, a loop using index \(i\) and \(i+1\) can visit \(i=0,1\) only. Its stopping bound is therefore smaller than the bound for visiting single values. See adjacent pair iteration.

Test the empty input and the smallest meaningful case

A length-one sequence performs one ordinary element visit and zero pair comparisons. A length-zero sequence performs neither. For a scan beginning by reading its first element, use a guard for an allowed empty input.

Try a table storing header plus data rows. If a source line number begins at one and the row offset begins at zero, preserve both roles during translation. Where slots are partitioned into batches, the end of one half-open batch should be the beginning of the next. Half-open slices make coverage and overlap easy to check on paper. Use distinctive names at the first and last positions so each missing visit is observable.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩