basics · beginner · ~15 min
Bound a scan so a missing NUL can't run off the end.
Measure a string's length but never scan past a fixed limit — like strnlen.
Implement int safe_strlen(const char *s, int max) that returns the length of s, but examines at most max bytes. If no NUL appears within the first max bytes, return max. This protects against a buffer that might not be NUL-terminated. No main — the grader calls it.
A character buffer s, and the maximum number of bytes to scan int max (>= 0).
Returns the smaller of the actual string length and max.
safe_strlen("abc", 10) -> 3
safe_strlen("abcdef", 3) -> 3 (capped at max)
safe_strlen("", 5) -> 0
max bytes, the result is max.A buffer s, and the max bytes to scan int max (>= 0).
min(strlen(s), max), as an int.
Scan at most max bytes; return max if no NUL is found in range.
int safe_strlen(const char *s, int max) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.