Arrays & Strings · beginner · ~8 min
Walk a string until the NUL terminator.
strlen is one of the smallest, most-used standard library functions. Implementing it teaches the canonical "walk a NUL-terminated string" loop:
size_t my_strlen(const char *s) {
const char *p = s;
while (*p) p++;
return (size_t)(p - s);
}
Use const char * for read-only string parameters — it documents intent and prevents accidental writes.
int for a length: lengths are non-negative and can be huge; use size_t.strlen(NULL) is undefined behaviour. Check before calling.