cybersecurity · intermediate · ~15 min · safe pentest lab

Replace unsafe strcpy with bounded copy

Apply the bounded-copy pattern as a focused refactor.

Challenge

You are given a function with the canonical buffer-overflow bug:

void greet(char *out, const char *name) {
    strcpy(out, "Hello, ");
    strcat(out, name);
}

Rewrite as int greet(char *out, size_t out_sz, const char *name): produce "Hello, <name>", return 0 on success or -1 if the result would overflow. Always NUL-terminate out.

Starter code

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

int greet(char *out, size_t out_sz, const char *name) {
    /* TODO: build "Hello, <name>" safely */
    return -1;
}

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