cybersecurity · intermediate · ~15 min

Fix the strcpy overflow

Bounded copy with explicit destination size + NUL termination.

Challenge

You are given a function with a classic buffer overflow:

void copy_label(char *out, size_t out_sz, const char *src) {
    strcpy(out, src);   // unsafe: blindly writes past out_sz
}

Rewrite it so it copies at most out_sz - 1 bytes, always NUL-terminates, and returns 0 on success / -1 if the input is too long. Signature: int copy_label(char *out, size_t out_sz, const char *src).

Why this matters

Replacing a strcpy with a bounded equivalent is the single most impactful defensive patch in C. This exercise builds the muscle memory of 'see strcpy → replace with snprintf or strlcpy'.

Starter code

#include <string.h>
#include <stddef.h>

int copy_label(char *out, size_t out_sz, const char *src) {
    /* TODO: copy safely, return 0 on success, -1 if too long */
    return -1;
}

Common mistakes

Using strncpy(dst, src, n) — it does NOT guarantee NUL-termination if src is exactly n bytes. Use snprintf(dst, n, "%s", src) or strlcpy(dst, src, n) instead.

Edge cases to handle

Source longer than dst — must truncate AND NUL-terminate. Source equal to dst's capacity — many APIs get this wrong.

Complexity

O(min(strlen(src), cap)).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.