A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strlen walks until it finds a null terminator. If the terminator is missing, it walks forever, reading past the buffer. strnlen takes a maximum length. It walks until it finds a null or reaches the limit, whichever comes first. It returns the number of characters before the null, or the limit if no null was found. This prevents the overread when you are not certain the buffer is properly terminated.
#include <stdio.h>#include <string.h>int main(void) {char terminated[] = "Hello";char unterminated[5] = {'H', 'e', 'l', 'l', 'o'};printf("strlen(terminated): %zu\n", strlen(terminated));printf("strnlen(terminated, 10): %zu\n", strnlen(terminated, 10));printf("strnlen(unterminated, 5): %zu\n", strnlen(unterminated, 5));printf("strnlen(unterminated, 3): %zu\n", strnlen(unterminated, 3));return 0;}
For the unterminated buffer, strnlen with a limit of 5 returns 5. It did not find a null, so it returned the maximum. strlen on the same buffer would read past the 5 bytes into adjacent memory. strnlen with a limit of 3 returns 3, stopping early. The limit is a safety bound, not a desired length.
strnlen is POSIX, not ISO C. It is available on Linux, macOS, BSD, and modern Windows UCRT. It is not available on all embedded toolchains. For portable code, you may need a fallback implementation or a compile-time check.
strnlen is the defensive alternative to strlen. Use it when processing data from files, networks, or any source where the null terminator might be missing. The extra argument costs nothing and prevents an entire class of overread bugs. Next: multiline string literals, a small syntax feature with practical uses in code generation and embedded SQL.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.