basics · beginner · ~15 min

Has a terminator in range?

Verify a buffer is NUL-terminated before treating it as a string.

Challenge

Verify a byte buffer is a safe C string before treating it as one.

Task

Implement int has_nul_within(const char *buf, int n) that returns 1 if a NUL byte ('\0') appears within the first n bytes of buf, else 0. A buffer with no NUL in range is not a valid C string and is unsafe to pass to str* functions. No main — the grader calls it.

Input

A byte buffer buf, and the number of bytes to inspect int n (>= 0).

Output

Returns 1 if a NUL is found within the first n bytes, otherwise 0.

Example

buf = {'h','i',0,'x','y'};   has_nul_within(buf, 5)   ->   1
buf = {'a','b','c'};         has_nul_within(buf, 3)   ->   0

Edge cases

  • A buffer with no NUL in the first n bytes returns 0.

Input format

A byte buffer buf, and the count int n (>= 0).

Output format

1 if a NUL appears within the first n bytes, otherwise 0.

Constraints

Inspect exactly n bytes.

Starter code

int has_nul_within(const char *buf, int n) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.