Skip to content
systemcoding.dev
Security

Off-by-One Errors in C String Handling

One byte too few for the terminating NUL is enough to corrupt memory. See the common off-by-one patterns in C strings and how to write them correctly.

6 min read
Summarize in AI
Flat illustration of a shield with a lock, a key and a password field, with the C, Rust and OpenSSL logos.

A C string is an array of characters followed by a NUL byte, and that last byte is the source of most off-by-one bugs. A string of five letters needs six bytes. Forget the sixth and the program writes one byte past the array, or reads one byte past it looking for an end that never comes. One byte sounds harmless. It is not, because a single stray NUL can clear the low byte of a neighboring pointer or a saved frame pointer. This post lists the patterns that produce the error, shows the output of a broken and a fixed program, and gives rules that avoid the whole class. Examples target GCC 15 on Linux 6.12 with glibc 2.41.

Length and size are different numbers

strlen("hello") returns 5, the characters before the terminator. sizeof("hello") is 6, because the literal is an array of six char. A buffer that stores the string needs strlen(s) + 1 bytes. Every off-by-one bug in this family is a place where the program counts characters and forgets the terminator, or counts bytes and forgets that the last one is reserved.

ExpressionValue for "hello"Meaning
strlen(s)5characters before the NUL
sizeof(s) for a literal or an array6bytes, terminator included
sizeof(p) for char *p8 on x86-64the pointer, not the string
bytes to allocate6strlen(s) + 1

The third row is a classic trap: sizeof on a pointer parameter gives the size of the pointer, so a function that receives char *buf cannot find the buffer size with it.

The malloc that is one byte short

dup.cc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static char *dup_string(const char *s)
{
    char *copy = malloc(strlen(s));   /* bug: no room for the NUL */
    if (copy == NULL)
        return NULL;
    strcpy(copy, s);                  /* writes strlen(s) + 1 bytes */
    return copy;
}

int main(void)
{
    char *p = dup_string("hello");
    printf("%s\n", p);
    free(p);
    return 0;
}

malloc(5) returns a block with at least five usable bytes, and strcpy writes six. The sixth byte lands in the allocator's padding on many systems, so the program often prints hello and exits cleanly. That is the danger: it passes tests. Under AddressSanitizer, built with gcc -std=c17 -g -fsanitize=address -o dup dup.c, the report names the exact line:

Text
==31877==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000015 at pc 0x7f1c4a0b1f2e bp 0x7ffd5b1d2a30 sp 0x7ffd5b1d21e0
WRITE of size 6 at 0x602000000015 thread T0
    #0 0x7f1c4a0b1f2d in strcpy (libasan.so.8+0x...)
    #1 0x5581b2c4e2a3 in dup_string dup.c:9
    #2 0x5581b2c4e2f8 in main dup.c:17
0x602000000015 is located 0 bytes after 5-byte region [0x602000000010,0x602000000015)

The addresses and process id differ on every run, but the line 0 bytes after 5-byte region is the signature of an off-by-one. The fix is one character:

c
char *copy = malloc(strlen(s) + 1);

In real code, prefer strdup, which is in POSIX.1-2008 and in C23 as strdup, and does the arithmetic for you.

The loop that runs one time too many

A second pattern is the loop bound. Arrays of size N have valid indexes 0 to N - 1, and <= instead of < reads or writes index N.

fill.cc
#include <stdio.h>

int main(void)
{
    char tag[4];
    for (int i = 0; i <= 4; i++)    /* bug: i reaches 4 */
        tag[i] = 'x';
    tag[3] = '\0';
    printf("%s\n", tag);
    return 0;
}

The iteration with i == 4 writes tag[4], one byte outside the array. With -fsanitize=address the report says stack-buffer-overflow and READ/WRITE of size 1. Without it, GCC 15 at -O2 -Wall may warn with -Warray-bounds, which is why -Wall -Wextra belongs in every build. The correct loop is for (int i = 0; i < 3; i++), followed by the terminator at tag[3].

strncpy does not terminate

Programmers who learn that strcpy is unsafe reach for strncpy, then trip on a different one-byte rule. strncpy(dst, src, n) copies at most n bytes and writes a terminator only if src is shorter than n. When src is n bytes or longer, dst is left without a NUL, and the next printf("%s") runs off the end.

trunc.cc
#include <stdio.h>
#include <string.h>

int main(void)
{
    char dst[5];
    strncpy(dst, "hello", sizeof dst);   /* copies 5 bytes, no NUL */
    printf("%.5s\n", dst);               /* safe: precision stops at 5 */
    dst[sizeof dst - 1] = '\0';          /* the manual fix */
    printf("%s\n", dst);
    return 0;
}
Text
hello
hell

The %.5s precision limits how far printf reads, so the first line is safe. Adding the terminator by hand keeps four characters. GCC 8 and later warn about this shape with -Wstringop-truncation, which is part of -Wall. Better than patching strncpy is to use snprintf(dst, sizeof dst, "%s", src), which always terminates and reports truncation through its return value. glibc 2.38 also added strlcpy and strlcat, which POSIX.1-2024 standardized.

The fencepost with fgets and read

fgets(buf, size, stream) reads at most size - 1 characters and always writes the terminator, so passing sizeof buf is correct. read(fd, buf, n) is different: it does not terminate at all, and it returns a byte count. Passing sizeof buf and then treating the buffer as a string is an off-by-one waiting to happen when the read fills it. Read at most sizeof buf - 1 bytes, and write the NUL at index n yourself:

c
ssize_t n = read(fd, buf, sizeof buf - 1);
if (n >= 0)
    buf[n] = '\0';

When n is sizeof buf - 1, the terminator goes to the last valid index. Skipping the - 1 makes buf[n] an out-of-bounds write on a full read, and a full read is exactly what an attacker sends.

Why one byte matters

An off-by-one write of a NUL is a real exploit primitive. On little-endian x86-64, clearing the lowest byte of a saved frame pointer moves it down by up to 255 bytes, so the caller's frame appears to start inside the attacker's buffer. This was demonstrated against software in the late 1990s, and it is why the stack protector exists. Heap versions corrupt the size field of the next chunk in the allocator. A single byte is also how a string stops being a string: the program then reads past the end for a strlen that never finds a terminator.

Rules that remove the class

  1. Allocate strlen(s) + 1, or call strdup.

  2. Compute sizes with sizeof on the array, never on a pointer parameter, and pass the size as an argument to functions.

  3. Write loops as i < n, and treat <= against a size as a red flag in review.

  4. Never rely on strncpy to terminate. Use snprintf, or terminate explicitly.

  5. After any call that copies bytes without a terminator (read, recv, memcpy), write the NUL yourself at a position you have checked.

  6. Build with -Wall -Wextra and test with -fsanitize=address,undefined, which catches the one-byte write at the line that did it.

Reviewing code for the pattern

Off-by-one errors survive review because the arithmetic looks plausible. A reviewer who wants to find them quickly can ask three questions of every buffer. What is the largest string that can arrive, counted in characters? Where does the code add one for the terminator? And what happens at exactly the boundary, with a string of length size - 1, of length size, and of length zero? Writing those three inputs as test cases is cheap, and they are the three inputs that expose most of the bugs above. A fourth input, a string of length size + 1, checks that the rejection path works at all.

A useful habit is to name the capacity and the limit separately in code. A constant NAME_MAX_CHARS of 7 and a buffer declared as char name[NAME_MAX_CHARS + 1] put the extra byte in plain sight, so the next reader does not have to rederive it. The same applies to loop bounds: iterate over sizeof name - 1 characters when you mean to leave room for the terminator, and say why in the name of the variable, not in a comment that drifts.

Taggedcbeginner
Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.