cybersecurity · intermediate · ~25 min
Per-character expansion with bounded output.
HTML-escape user text so it renders as literal characters instead of being interpreted as markup — the primary defense against XSS.
Implement int html_escape(const char *in, char *out, size_t cap) that copies in into out, replacing each HTML-significant character with its entity:
| char | replacement |
|---|---|
& |
& |
< |
< |
> |
> |
" |
" |
' |
' |
All other characters are copied unchanged. Always NUL-terminate out.
in: a NUL-terminated ASCII string the grader provides.out: the destination buffer.cap: the capacity of out in bytes (cap >= 1).Returns the number of bytes written to out, excluding the terminating NUL. Returns -1 if the escaped result (plus its NUL) would not fit in cap.
html_escape("plain", out, 256) -> 5, out = "plain"
html_escape("<b>&'\"a", out, 256) -> >0, out = "<b>&'"a"
html_escape("&&&&&", out, 5) -> -1 (won't fit)
html_escape("", out, 256) -> 0, out = ""
malloc). Reserve one byte for the NUL when checking capacity.HTML escaping is the primary defense against XSS. Hand-rolling the escape teaches you exactly which characters carry meaning in HTML.
A NUL-terminated ASCII string in, a destination out, and its capacity cap (>= 1).
Bytes written excluding the NUL; -1 if the result would not fit. out is always NUL-terminated.
No malloc; cap >= 1; reserve a byte for the NUL.
#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.