The standard library’s strlen() counts characters in a string by walking from the first character until it reaches the null terminator ('\0') — the zero byte that marks the end of every C string. Implementing strlen() yourself is a classic exercise that teaches exactly how strings work in C.
The original post had two serious problems: (1) it used gets(), which has a buffer overflow vulnerability and was removed from C11; (2) its loop condition was string[i] != ' ' (a space character, ASCII 32), instead of string[i] != '\0' (the null terminator, ASCII 0). This means the original program counted characters only until the first space — “hello world” would return 5, not 11. Any string without a space would scan past the end into uninitialized memory (undefined behavior).
The Bug Explained
| Loop condition | “hello” | “hello world” | “nospaces” |
|---|---|---|---|
!= ' ' (space — WRONG) |
5 (luck) | 5 (WRONG) | UB — no space found |
!= '\0' (null — CORRECT) |
5 ✓ | 11 ✓ | 8 ✓ |
C Program: strlen Without the Built-in
/* Implement strlen without the built-in function
* Compile: gcc -ansi -Wall -Wextra mystrlen.c -o mystrlen */
#include <stdio.h>
#include <string.h> /* for comparison with strlen() */
int my_strlen(const char *s)
{
int len = 0;
while (s[len] != '\0')
len++;
return len;
}
int main(void)
{
char str[256];
printf("Enter a string: ");
if (fgets(str, sizeof(str), stdin) == NULL) return 1;
str[strcspn(str, "\n")] = '\0';
printf("Length (my_strlen) = %d\n", my_strlen(str));
printf("Length (strlen) = %d\n", (int)strlen(str));
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra mystrlen.c -o mystrlen
./mystrlen
Sample Output
Enter a string: hello Length (my_strlen) = 5 Length (strlen) = 5 Enter a string: hello world Length (my_strlen) = 11 Length (strlen) = 11 Enter a string: Length (my_strlen) = 0 Length (strlen) = 0
How C Strings Work in Memory
Every C string is a sequence of char values terminated by a null byte ('\0', value 0). For “hello”:
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Character | ‘h’ | ‘e’ | ‘l’ | ‘l’ | ‘o’ | ‘\0’ |
| ASCII value | 104 | 101 | 108 | 108 | 111 | 0 |
The length is 5 — the number of characters before the null terminator, not including it.
Code Explanation
while (s[len] != '\0')— the loop incrementslenfor every character that is not the null terminator. When it hits'\0',lenholds the number of characters before it — exactly the string length. The original used!= ' '(space, ASCII 32), which stopped at the first space instead of the end of the string.const char *s— the parameter isconstbecausemy_strlenreads but never modifies the string. Marking itconstallows passing string literals (which cannot be modified) and signals to the caller that the string is safe.fgetsreplacesgets—gets()does not check buffer bounds and can overflow the array if the input is longer than the buffer. It was deprecated in C99 and removed in C11.fgets(str, sizeof(str), stdin)reads at mostsizeof(str)-1characters and always null-terminates. Thestrcspncall strips the trailing newline thatfgetsincludes.- Alternative: pointer arithmetic —
strlencan also be implemented with a pointer:const char *p = s; while (*p) p++; return (int)(p - s);. This avoids the index variable. Both are correct; the index version is easier to read for beginners.
What This Program Teaches
- Null terminator, not space — the null byte (
'\0') is the end-of-string sentinel in C. Do not confuse it with space (' '), newline ('\n'), or zero the digit ('0'). They are all different characters. - gets() is unsafe, always — if you see
gets()in old code, replace it withfgets(). There is no safe way to usegets(). It is one of the most common sources of buffer overflow vulnerabilities. - Checking against library output — printing both
my_strlen()andstrlen()lets you verify your implementation against the trusted library function. This is the standard technique for validating custom implementations of standard functions.
Related Programs
- String Concatenation in C
- Compare Two Strings in C
- Substring Search in C
- Toggle Case of a String in C
- String Functions in C — Complete Reference
Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
|
C Programming: A Modern Approach — K.N. King (India) |
(US)
Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.