Off-by-One Errors (CWE-193)
An off-by-one error is a calculation or comparison that is wrong by exactly one: <= where < was meant, a size that forgot the NUL terminator, a loop that runs n + 1 times. They are the most human of memory bugs, because the code looks right and works on almost every input. In C they matter because the one extra byte is written or read just outside an object, and one byte is enough: a single NUL written past a stack buffer can change the low byte of a saved frame pointer, and a single byte into the next heap chunk's size field can change how the allocator merges chunks. Off-by-one writes have been behind exploitable bugs in sudo, mail servers and many parsers.
The three classic shapes
| Shape | Example | What goes wrong |
|---|---|---|
| Forgotten terminator | malloc(strlen(s)) then strcpy |
the NUL lands one byte past the block |
| Inclusive bound | for (i = 0; i <= n; i++) a[i] = … |
the last iteration touches a[n] |
| Fencepost counting | "from index 3 to index 7" is 5 elements, not 4; end - start vs end - start + 1 |
sizes and loop counts disagree by one |
The toolkit lesson already showed an inclusive bound (i <= n reading one int too many). This lesson takes the forgotten terminator, in a function every code base has.
The bug in a toy program
join builds "dir/file". The size calculation remembers the / but not the NUL, so the result needs one byte more than it gets. The plain build prints a correct path, because the extra byte lands in the allocator's rounding slack (an 18-byte request gets 24 usable bytes, see the heap lesson). ASan poisons everything past the 18 requested bytes:
cat > path.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Joins dir and file as "dir/file". */
static char *join(const char *dir, const char *file) {
size_t n = strlen(dir) + strlen(file) + 1; /* BUG: room for '/', none for the NUL */
char *out = malloc(n);
memcpy(out, dir, strlen(dir));
out[strlen(dir)] = '/';
strcpy(out + strlen(dir) + 1, file);
return out;
}
int main(void) {
char *p = join("/srv/lab", "notes.txt");
printf("%s\n", p);
free(p);
return 0;
}
SRC
gcc -g -O0 path.c -o path && ./path && echo "plain build: looks fine"
gcc -g -O0 -fsanitize=address path.c -o path-asan && ./path-asan 2>&1 | grep -E 'ERROR|WRITE|#1 |located|^=>'
echo "exit code: ${PIPESTATUS[0]}"/srv/lab/notes.txt
plain build: looks fine
==21==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x503000000052 at pc 0x75c52cf88923 bp 0x7ffeffff3640 sp 0x7ffeffff2de8
WRITE of size 10 at 0x503000000052 thread T0
#1 0x5b090d4e3366 in join /home/learner/path.c:11
0x503000000052 is located 0 bytes after 18-byte region [0x503000000040,0x503000000052)
allocated by thread T0 here:
#1 0x5b090d4e32cf in join /home/learner/path.c:8
=>0x503000000000: fa fa 00 00 00 fa fa fa 00 00[02]fa fa fa fa fa
exit code: 1
The report, line by line
heap-buffer-overflow … WRITE of size 10: thestrcpywrites"notes.txt"(9 characters) plus its NUL, 10 bytes.#1 join path.c:11: thestrcpyline.0 bytes after 18-byte region, allocated atpath.c:8:"/srv/lab"(8) +"notes.txt"(9) + 1 = 18 bytes requested, but"/srv/lab/notes.txt"plus its NUL needs 19.- The shadow line
00 00[02]: two full granules (16 bytes) and a partial granule with only 2 addressable bytes, 16 + 2 = 18. The 19th byte is the first poisoned one. This is how ASan can catch a single byte even when the allocator would round the block up.
Why a single byte can matter
In this toy the byte lands in slack and nothing happens. Change the lengths so that the request is exactly 24 bytes (or 40, 56: any 16k + 8, where the usable size equals the request) and the NUL lands exactly on the next chunk's size field, clearing its lowest byte, which includes the PREV_INUSE flag. On the stack, the same NUL past a buffer that sits right under the saved frame pointer zeroes that pointer's lowest byte, so the caller later uses a frame slightly lower in memory. Both were turned into working exploits in real software. Whether a given off-by-one is harmless depends on layout details that change with the compiler, the allocator and the input lengths, so every one is fixed, never argued about.
The fix
Compute the length once, include the terminator, and use one bounded call that also reports truncation. snprintf returns the length it needed, which makes the size check trivial:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns a new "dir/file" string, or NULL. */
static char *join(const char *dir, const char *file) {
int need = snprintf(NULL, 0, "%s/%s", dir, file); /* length without the NUL */
if (need < 0) return NULL;
char *out = malloc((size_t)need + 1);
if (!out) return NULL;
snprintf(out, (size_t)need + 1, "%s/%s", dir, file);
return out;
}
/* The boundary tests: the result must be exactly strlen(dir) + 1 + strlen(file) long. */
int main(void) {
const char *dirs[] = {"/srv/lab", "", "/"}, *files[] = {"notes.txt", "a", ""};
for (int i = 0; i < 3; i++) {
char *p = join(dirs[i], files[i]);
size_t want = strlen(dirs[i]) + 1 + strlen(files[i]);
printf("\"%s\" length %zu, expected %zu: %s\n", p, strlen(p), want, strlen(p) == want ? "ok" : "WRONG");
free(p);
}
return 0;
}"/srv/lab/notes.txt" length 18, expected 18: ok
"/a" length 2, expected 2: ok
"//" length 2, expected 2: ok
The empty strings are deliberate: off-by-one bugs live at the edges, so the tests use the smallest inputs (empty, one character) as well as a normal one. Under ASan, the old join fails every one of these tests; the new one passes them.
How off-by-one errors are detected
- ASan: partial-granule shadow bytes (
01–07) catch single-byte overruns of any size of block. - Boundary tests: for every buffer size N, test inputs of length N − 1, N and N + 1. Fuzzers find these quickly because they mutate lengths.
- Review heuristics: every
<=in a loop over an array, everymalloc(strlen(…))without+ 1, everybuf[sizeof buf] = …, everystrncat(dst, src, sizeof dst)(the bound must besizeof dst - strlen(dst) - 1), and every place where an inclusive range becomes a count. - Compilers warn about some constant cases:
-Warray-boundsfora[n]with a knownn,-Wstringop-overflowfor constant string copies.
The CWE
CWE-193: Off-by-one Error names the calculation mistake; the memory effect is CWE-787 (out-of-bounds write) or CWE-125 (out-of-bounds read). Advisories usually record both.
Pitfalls
- "It works with glibc": the slack hides the bug until another allocator, a different length or ASan reveals it.
- Half-fixes: changing
<=to<in one loop while another loop over the same array keeps<=. Search the whole function. - Counting characters vs bytes: a UTF-8 string of 5 characters can be 15 bytes; size buffers in bytes.
Practice
1. For join("/srv", "x"), how many bytes does the buggy version allocate and how many does it need?
It allocates 4 + 1 + 1 = 6; it needs "/srv/x" (6) plus the NUL, 7.
2. Is char b[8]; for (int i = 1; i <= 8; i++) b[i - 1] = 'x'; an off-by-one?
No: it writes b[0] to b[7]. But b is not terminated, so passing it to printf("%s") would read past the end, a different bug.
3. What should the shadow byte of the last granule be for a 21-byte block?
21 = 16 + 5: two 00 granules and one 05.
Test yourself
Why did the plain build print a correct path?
- There was no bug
- The extra NUL landed in glibc's rounding slack (18 bytes requested, 24 usable), so nothing visible broke
- glibc fixed the size
- strcpy checks sizes
What does the shadow byte 02 mean in that report?
- Two bytes were freed
- Only the first 2 bytes of that 8-byte granule are addressable: 16 + 2 = 18
- The write was 2 bytes
- Two errors
Which inputs make the best tests for a buffer of size N?
- Random lengths
- Lengths N - 1, N and N + 1, plus empty input
- Only very long inputs
- Only valid inputs
What is the correct bound for strncat(dst, src, n) into char dst[64]?
- 64
- sizeof dst
- sizeof dst - strlen(dst) - 1
- strlen(src)