Skip to content
BetterDL

Off-by-one error

Also called: off-by-one, fencepost error, fence-post error, OBOE

A mistake where a count or boundary is one too high or one too low, such as taking N rather than N − 1 as the last address of an N-word memory.

An off-by-one error gets an answer wrong by exactly one. In memory work it nearly always comes from forgetting that addresses start at 0, or that a range includes both ends.

The three places it bites:

  • Last address. N words have addresses 0 to N − 1. A 4K memory ends at 4095 (FFF₁₆), not 4096.
  • Size of a range. From S to E inclusive there are E − S + 1 words, not E − S.
  • End of a block. N words starting at S end at S + N − 1, not S + N.

The classic picture is a fence: a 10-meter fence with posts every meter needs 11 posts. Count the posts (addresses), not the gaps between them.

A quick self-check for memory: the last address of a whole memory, or of a block starting at a multiple of its size, is all 1s in its low bits, so it ends in F digits in hex (possibly after a leading 1, 3 or 7). If your end address is a round number like 4000₁₆, you've probably landed on the next block's first address. See address range.

1
16³
F
16²
F
16¹
F
16⁰

Worked example

Example

Two slips, caught

A student says the range 5000₁₆ to 6000₁₆ is exactly 4K words, and that a 2K block at 1800₁₆ ends at 2000₁₆.

  1. 1.

    First claim: 6000₁₆ − 5000₁₆ + 1 = 1001₁₆ words, one more than 4K. The 4K block is 5000₁₆ to 5FFF₁₆.

  2. 2.

    Second claim: 2K = 800₁₆, so the block ends at 1800₁₆ + 800₁₆ − 1 = 1FFF₁₆.

  3. 3.

    2000₁₆ is the first address of the next block. Notice the warning sign: a round number.

Common mistakes

  • Giving N as the last address of an N-word memory. It's N − 1, because the first is 0.

  • Dropping the +1 when counting a range. Both ends are included.

Practice Off-by-one error

Interactive questions with instant feedback and a worked solution for every wrong answer.

Learn it step by step

Off-by-one error is taught in Memory and Counters.