basics · beginner · ~15 min

Bounded string length

Bound a scan so a missing NUL can't run off the end.

Challenge

Measure a string's length but never scan past a fixed limit — like strnlen.

Task

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.

Input

A character buffer s, and the maximum number of bytes to scan int max (>= 0).

Output

Returns the smaller of the actual string length and max.

Example

safe_strlen("abc", 10)      ->   3
safe_strlen("abcdef", 3)    ->   3     (capped at max)
safe_strlen("", 5)          ->   0

Edge cases

  • If no NUL is found within max bytes, the result is max.
  • An empty string returns 0.

Input format

A buffer s, and the max bytes to scan int max (>= 0).

Output format

min(strlen(s), max), as an int.

Constraints

Scan at most max bytes; return max if no NUL is found in range.

Starter code

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.