Off-by-One
An off-by-one error uses an index or a length that is one too large or one too small. In C that is often a write to a[n] of an n-element array, or a string that lost its terminator.
Detailed Explanation
Arrays are 0 .. n-1. The first illegal index is n. A loop written for (i = 0; i <= n; i++) visits a[n]. A loop written for (i = 1; i < n; i++) skips a[0]. Both are off-by-one. The first is also a buffer overflow.
Strings need n + 1 bytes for n characters. char buf[4]; strcpy(buf, "abcd"); writes five bytes (a b c d \0) into four. malloc(strlen(s)) without + 1 is the same bug on the heap.
Half-open ranges [lo, hi) make the end index the length and make empty ranges lo == hi. Binary search, slices, and memcpy(dest, src, hi - lo) all get simpler. Inclusive ends (lo through hi including hi) force + 1 in every length and are where fenceposts hide.
strncpy(dest, src, sizeof dest) can fill dest with no terminator: that is an off-by-one on the terminator. snprintf always terminates when the size is at least 1, and its return is the untruncated length, which is easy to treat as "bytes written" and then overflow the next time.
Unsigned wrap is a cousin. size_t i = 0; i--; is a huge index, not -1. A loop that decrements past zero is an off-by-one that became an overflow.
Test empty inputs, length 1, and full buffers. Off-by-ones live on the edges. A fuzz test that only sends huge strings will miss n = 0.
Code Examples
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static char *dup_str(const char *s)
{
size_t n = strlen(s) + 1; /* +1 for '\0' */
char *p = malloc(n);
if (p == NULL) {
return NULL;
}
memcpy(p, s, n);
return p;
}
int main(void)
{
char *p = dup_str("abc");
if (p == NULL) {
return 1;
}
printf("%zu\n", strlen(p)); /* prints: 3 */
free(p);
return 0;
}#include <stdio.h>
int main(void)
{
int a[3] = { 1, 2, 3 };
int n = 3;
for (int i = 0; i < n; i++) { /* i < n, not i <= n */
printf("%d ", a[i]);
}
printf("\n"); /* prints: 1 2 3 */
return 0;
}Common Gotchas
`a[n]` is out of bounds for `int a[n]`
the last element is `a[n-1]`.
`malloc(strlen(s))` is one byte short
the terminator needs a home.
`for (size_t i = n; i >= 0; i--)` is infinite
unsigned `i >= 0` is always true.
Half-open `[0, n)` makes the number of elements `n` and the first invalid index
Half-open `[0, n)` makes the number of elements `n` and the first invalid index `n`