Where the buffer ends

Making an off-by-one boundary visible with a minimal local harness.

The challenge

This sample examines a fixed-size destination buffer. The question is how much room remains for a terminating null byte after copying a string.

Write down the invariant

For an eight-byte buffer holding a C string, at most seven bytes may belong to the payload. The eighth byte is reserved for the terminator.

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

int main(void) {
    char destination[8];
    const char *source = "sample";
    size_t length = strlen(source);

    if (length >= sizeof destination) {
        return 1;
    }
    memcpy(destination, source, length + 1);
    puts(destination);
    return 0;
}

Local verification

Save the example as boundary.c, then compile it with warnings and sanitizers enabled:

cc -Wall -Wextra -fsanitize=address,undefined boundary.c -o boundary
./boundary

Test empty, seven-byte and eight-byte strings. The first two should succeed; the third should be rejected before the copy.

Lessons learned

Document the invariant beside the boundary check. A sanitizer helps expose mistakes during testing, but does not replace length validation.