cybersecurity · intermediate · ~15 min
Bounded copy with explicit destination size + NUL termination.
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).
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'.
#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;
}
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.
Source longer than dst — must truncate AND NUL-terminate. Source equal to dst's capacity — many APIs get this wrong.
O(min(strlen(src), cap)).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.