Off-by-One Errors in C: The Bug That Hides in Plain Sight

By TheCodingCove · 6 min read · Updated November 8, 2026

An off-by-one error happens when a loop runs one time too many or one time too few, or when you use an index that is one position away from the right one. These bugs are common because the mistake is tiny: a single <= that should have been <.

Arrays start at zero

int a[5];   /* valid indexes are 0, 1, 2, 3 and 4 */

An array of 5 elements has indexes 0 to 4. There is no a[5].

Mistake 1: using <= instead of <

int a[5];
int i;

for (i = 0; i <= 5; i++)
{
    a[i] = i;   /* a[5] is out of bounds */
}

The last pass writes to a[5], which is outside the array. This is undefined behavior. It might overwrite a neighboring variable, crash the program or seem to work. The fix is i < 5.

Mistake 2: forgetting the null terminator

A C string needs one extra byte for the '\0' that marks its end.

char word[6] = "hello";   /* 5 letters + 1 terminator */

The same mistake appears when you copy strings into allocated memory:

char *copy = malloc(strlen(src));       /* too small by one byte */
char *copy = malloc(strlen(src) + 1);   /* correct */

Mistake 3: counting fence posts

A fence with 5 posts has only 4 gaps between them. Code that compares each element with the next one has the same shape.

for (i = 0; i < n; i++)
{
    if (a[i] > a[i + 1])   /* on the last pass a[i + 1] is a[n] */
    {
        /* ... */
    }
}

The loop should stop one step earlier with i < n - 1.

Mistake 4: starting at 1 by habit

Humans count from 1 but C arrays count from 0. A loop such as for (i = 1; i <= n; i++) skips the first element and reads past the last one.

How to prevent off-by-one errors

  • Use the pattern for (i = 0; i < n; i++) as your default and question every deviation
  • Define the size once with a constant, or calculate it with sizeof(a) / sizeof(a[0])
  • Write down the first and last valid index before you write the loop
  • Test the edge cases: an empty array, one element and a completely full array
  • Compile with gcc -g -fsanitize=address, which reports a "stack-buffer-overflow" with the exact line

These errors often lead to crashes, so it is worth reading segmentation faults in C next. If loops themselves still feel shaky, the C Programming notes walk through them one step at a time.

Learn C step by step

Our beginner-friendly PDF notes explain pointers, memory and loops with analogies and worked examples.

See the C Programming notesWatch free videos

Keep reading