cybersecurity · beginner · ~12 min
Build a bounded-buffer text formatter with `snprintf` and proper overflow handling.
Implement:
typedef struct {
const char *title;
const char *severity;
const char *asset;
const char *evidence;
const char *recommendation;
} finding_t;
int render_finding(const finding_t *f, char *out, size_t cap);
Render f into out as Markdown. Return the number of bytes written
(excluding the trailing NUL), or -1 if the buffer would overflow.
## <title>
**Severity:** <severity>
**Asset:** <asset>
### Evidence
<evidence>
### Recommendation
<recommendation>
snprintf. Check its return value: < 0 or >= cap → return -1.f, NULL out, or cap == 0 → return -1.f → return -1.snprintf with the whole template is simplest. The format string spans seven %s substitutions.int n = snprintf(out, cap, fmt, title, severity, asset, evidence, recommendation); if (n < 0 || (size_t)n >= cap) return -1; return n;snprintf returns the count it WOULD have written if the buffer were big enough — so n >= cap means overflow.Findings without a writeup don't ship. A bounded snprintf formatter turns a struct into a deliverable.
A pointer to a finding_t + an output buffer + its capacity.
Bytes written (excluding NUL), or -1 on any failure.
Use snprintf. Check overflow. Return -1 on any NULL.
#include <stddef.h>
typedef struct {
const char *title;
const char *severity;
const char *asset;
const char *evidence;
const char *recommendation;
} finding_t;
int render_finding(const finding_t *f, char *out, size_t cap) {
/* TODO */
(void)f; (void)out; (void)cap;
return -1;
}
Trusting snprintf's return without checking against cap. Forgetting the blank lines between sections. NULL inputs not rejected.
Tiny buffer → -1. NULL pointer or NULL field → -1. Exact-fit buffer → bytes match strlen(out).
O(n) where n is the sum of input string lengths.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.