Arrays & Strings · beginner · ~8 min

Implementing strlen

Walk a string until the NUL terminator.

Lesson

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.

Common mistakes

  • Returning a signed int for a length: lengths are non-negative and can be huge; use size_t.
  • Forgetting that strlen(NULL) is undefined behaviour. Check before calling.