Avoiding off-by-one errors in loops
What you'll learn: How to correctly set loop boundaries to prevent accessing memory outside of your array.
The Fencepost Problem
Imagine you are building a 10-meter fence with posts every 1 meter. You might instinctively think you need 10 posts, but you actually need 11 to cover both ends. In programming, we encounter the opposite struggle. Because C arrays are zero-indexed, a 10-element array starts at index 0 and ends at index 9.
An "off-by-one" error happens when your loop tries to visit index 10. Since that index doesn't belong to your array, your program might crash, or worse, silently grab "garbage" data from a neighbor's memory.
The < vs. <= Trap
The most common way to iterate through an array is a for loop. The "stopping condition" in the middle of the for header is where most mistakes happen.
If you have an array of size 5, you want to touch indices 0, 1, 2, 3, 4.
- Correct:
i < 5(Stops before hitting 5) - Incorrect:
i <= 5(Attempts to access index 5, which is out of bounds)
Practical Example
Look at how we safely traverse this list of scores. Pay close attention to the condition in the loop header.
#include <stdio.h>
int main() {
int scores[5] = {88, 92, 79, 94, 85};
int num_elements = 5;
// Use < to stay within the 0-4 range
for (int i = 0; i < num_elements; i++) {
printf("Score at index %d is %d\n", i, scores[i]);
}
return 0;
}
If we had used i <= num_elements, the loop would have tried to print scores[5]. In C, the computer doesn't always stop you from looking at index 5; it just gives you whatever random, broken data happens to be sitting in the RAM immediately after your array. This leads to "heisenbugs"—bugs that appear and disappear randomly.
Summary Checklist
To stay safe, always verify two things:
- Start at 0: Ensure your counter begins at the first valid index.
- Use Strictly Less Than: When using the array's size as a boundary, the
<operator is your best friend.
Key takeaway
Always use i < size instead of i <= size to ensure your loop stops exactly one step before the boundary.