Implement strlen
Implement size_t my_strlen(const char *s) that returns the number of characters before the terminating '\0', without using the standard library.
Example: my_strlen("hello") → 5, my_strlen("") → 0.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Walk the string until you reach '\0'. Count with a size_t, not an int. You can count with an index or by subtracting two pointers.
#include <stdio.h>
#include <stddef.h>
size_t my_strlen(const char *s)
{
const char *p = s;
while (*p)
p++;
return (size_t)(p - s); /* distance from start to the '\0' */
}
Your index version (while (s[len] != '\0') len++;) is correct. The pointer version above does the same thing: advance to the terminator and subtract the start address.
Walk-through: "abc"
| p points at | *p |
action |
|---|---|---|
| s + 0 | 'a' | p++ |
| s + 1 | 'b' | p++ |
| s + 2 | 'c' | p++ |
| s + 3 | '\0' | stop, return 3 |
Points interviewers check:
- Return type size_t: lengths are never negative and can exceed INT_MAX. A common follow-up bug is for (int i = 0; i < strlen(s) - 1; i++): for an empty string, strlen(s) - 1 is a huge unsigned number.
- O(n) every call: calling strlen in a loop condition makes the loop O(n²). Compute it once.
- NULL: the standard strlen(NULL) is undefined; don't hide bugs by returning 0 silently.
- No terminator: on a buffer filled from a UART or network packet there may be no '\0', and strlen reads past the end. Use a bounded version (strnlen(s, maxlen)) for untrusted data.
Faster versions check one word at a time once the pointer is aligned, using the zero-byte trick (v - 0x01010101) & ~v & 0x80808080 from the Bit Manipulation topic.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(my_strlen("hello") == 5);
CHECK(my_strlen("") == 0);
CHECK(my_strlen("a") == 1);
CHECK(my_strlen("embedded interview") == 18);
char buf[] = { 'a', 'b', '\0', 'c', '\0' };
CHECK(my_strlen(buf) == 2); /* stops at the first NUL */
const char *s = "\xFF\x80 high bytes";
CHECK(my_strlen(s) == 13);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}