cybersecurity · intermediate · ~25 min
Per-character expansion with bounded output.
Implement int html_escape(const char *in, char *out, size_t cap). Replace:
& → &< → <> → >" → "' → 'NUL-terminate out. Return bytes written (excluding NUL), or -1 if it wouldn't fit.
HTML escaping is the primary defense against XSS. Hand-rolling the escape teaches you exactly which characters carry meaning in HTML.
in null-terminated ASCII.
See API.
No malloc. Cap >= 1.
#include <stddef.h>
int html_escape(const char *in, char *out, size_t cap) { /* TODO */ return -1; }
Escaping & last (your earlier & -> & then gets re-escaped); using ' -> ' (not valid in HTML4); using bare snprintf-per-char (slow).
Empty input. Input with no special chars. Buffer too small mid-escape.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.