cybersecurity · intermediate · ~15 min
Distinguish "permissive" parsing from strict input validation — a foundational security mindset.
Parse an integer strictly: accept only a clean signed-decimal string and reject everything else.
Implement int parse_safe_int(const char *s, int *out) that accepts a string made up only of an optional leading - followed by one or more decimal digits, stores the value in *out, and returns 0. Anything else returns -1. No main — the grader calls it.
s: the candidate string (NUL-terminated).out: pointer that receives the parsed value on success.Returns 0 and sets *out for a valid string; returns -1 for an invalid one.
parse_safe_int("42", &v) -> 0, v = 42
parse_safe_int("-7", &v) -> 0, v = -7
parse_safe_int(" 5", &v) -> -1 (leading space)
parse_safe_int("+5", &v) -> -1 (plus sign)
parse_safe_int("5abc", &v) -> -1 (trailing junk)
parse_safe_int("", &v) -> -1
-, leading/trailing whitespace, a + sign, or any trailing non-digit all fail.A candidate string s and an out pointer for the result.
0 with *out set for a clean signed-decimal string; -1 otherwise.
Allow only optional leading - and digits; reject spaces, +, and trailing junk.
int parse_safe_int(const char *s, int *out) {
/* TODO */
return -1;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.