Off-by-one errors and other classic beginner bugs (and how to spot them)
Some bugs are so common they have names. Knowing them makes them much easier to spot.
Off-by-one errors. Looping one time too many or too few. Common causes: lists that start at index 0, using <= instead of <, or confusing "the number of items" with "the last index." Ranges are a frequent source because some functions include the end value and others don't.
Assignment vs comparison. Writing = when you meant == (or === in JavaScript). Some languages catch it; others quietly assign and continue.
Mutating while iterating. Removing items from a list while looping over it often skips elements. Loop over a copy or build a new list instead.
Integer division surprises. In some languages, 5 / 2 gives 2, not 2.5.
Shadowed variables. Declaring a variable inside a block with the same name as one outside, then wondering why the outer value never changes.
Shared references. Copying a list or object by assigning it to a new variable, then modifying "the copy" and changing the original too.
Habits that help:
- Test the edge cases: empty input, one item, the last item
- Print or inspect values at boundaries
- Read the documentation for whether a range includes its end
What's the beginner bug that took you the longest to find? Any tricks for catching off-by-one errors early?
Comments · 4
Fencepost errors are the classic. Count 10 posts with 9 gaps between them, and many bugs make sense.
Also: forgetting that arrays start at zero. Lost track of how often that one costs people a night.
Any tips for finding these quickly, besides print debugging?
Write down what you expect the loop to do for a tiny input like 0, 1 or 2 items. Boundary cases expose most off-by-one problems quickly.