- How C strings are stored in memory (arrays with a null terminator)
- Why finding the length requires walking the string
- How to write your own version of
strlen() - How
const char *protects the input from modification - Why
size_tis the "correct" return type for a length function
How C stores strings — and why length needs counting
In C, a string isn't a special data type — it's just an array of char, with a special character '\0' (the null terminator, numeric value 0) marking the end. So "hello" is stored as 6 bytes: 'h', 'e', 'l', 'l', 'o', '\0'. The visible characters are 5, but the array is 6 bytes long. The null terminator is not part of the string's content — it's a sentinel that tells functions where the content ends.
This is the key difference from many other languages. In Python, JavaScript, or Java, a string object knows its own length — the length is stored in a header or field somewhere, and calling len(s) or s.length is O(1). In C, there's no such field. The string is just bytes in memory. To find the length, you have to walk through the bytes one at a time until you see the null terminator. That's O(n) — proportional to the string's length. It's not slow, but it's not free either.
Writing your own stringLength function is one of the simplest exercises in C — the body is a short loop — but it teaches something fundamental: strings in C are a convention, not a data type. The convention is "an array of chars ending in '\0'," and every string operation (length, comparison, concatenation) has to respect that convention. Once you understand this, C string functions stop feeling mysterious and start feeling mechanical. They're all just loops over bytes, looking for the terminator.
A note on the library version: C's standard library provides strlen() in <string.h>, and it does exactly what our function does — just with aggressive optimizations (word-at-a-time reading, SIMD on some platforms). In real code, you should use strlen() — it's faster and battle-tested. The point of writing your own is understanding the mechanism, not replacing the library. Once you've written it once, you'll never be confused about what strlen does internally.
💡 In one line: loop through the string, incrementing a counter as long as the current character isn't '\0'. When the loop ends, the counter is the length — the number of characters before the null terminator.
Designing the stringLength function
The signature has a couple of choices worth thinking about:
| Part | Choice | Why |
|---|---|---|
| Function name | stringLength | Descriptive, and doesn't clash with the library's strlen. Names like len or size are too generic. |
| Parameter | const char *s | const promises the function won't modify the input. char * is a pointer to the first character. |
| Return type | size_t | An unsigned integer type designed for sizes and lengths. Matches strlen's return type. Practically, it's the same as unsigned long on most platforms. |
The prototype:
size_t stringLength(const char *s);
And the definition — the simplest possible loop:
size_t stringLength(const char *s) {
size_t count = 0;
while (s[count] != '\0') {
count++;
}
return count;
}
That's the whole function. A loop, a counter, a check for the terminator. Any version that does more is more complex than necessary. There's a slightly more compact version that uses pointer arithmetic instead of indexing:
size_t stringLength(const char *s) {
const char *p = s;
while (*p) {
p++;
}
return p - s;
}
Here, p walks through the string until it reaches the null terminator, then returns p - s — pointer subtraction, which gives the number of elements between the two pointers. Since both are char *, that's the number of characters. This version is equally correct and slightly shorter, but the indexed version is arguably clearer for a first read. Both work; pick whichever you find more readable.
Why size_t and not int? Because lengths are never negative, and int's maximum (about 2.1 billion on most systems) is less than the maximum possible string size. size_t is guaranteed to be able to represent the size of any object in memory, which is exactly what a length function needs. The C standard library uses size_t for strlen, and there's no good reason to deviate. It also matches the types used by malloc, memcpy, and other memory functions, so passing a size_t length into those functions is type-correct.
A note on const: the parameter is const char *s, which means "pointer to a character that this function won't modify." This is both a promise to the caller (your string is safe) and a contract for the compiler (it can warn you if you accidentally try to write through s). It's a good habit to use const on every parameter that the function doesn't modify — the compiler enforces it, and it makes the function's intent clear.
🎯 Key idea: the null terminator ('\0') is the sentinel that lets C strings know where they end. Without it, length functions would read past the string's end, into whatever memory happens to be next — a classic buffer-overrun bug.
Complete C Program
Program: find the length of a user-entered string
#include <stdio.h>
#include <stddef.h> /* for size_t */
/* Function prototype */
size_t stringLength(const char *s);
int main(void) {
char buffer[200];
printf("Enter a string: ");
if (!fgets(buffer, sizeof(buffer), stdin)) {
return 1;
}
/* fgets keeps the trailing newline — that counts as part of the length */
size_t len = stringLength(buffer);
printf("Length (including newline): %zu\n", len);
/* Optional: strip the newline and recount */
for (size_t i = 0; i < len; i++) {
if (buffer[i] == '\n') {
buffer[i] = '\0';
break;
}
}
printf("Length (without newline): %zu\n", stringLength(buffer));
return 0;
}
/* Manual strlen — walk until the null terminator */
size_t stringLength(const char *s) {
size_t count = 0;
while (s[count] != '\0') {
count++;
}
return count;
}
The first length includes the newline character that fgets appends (unless the input was longer than the buffer). The second length strips the newline and recounts. The difference demonstrates an important point: what counts as a "length" depends on what you consider part of the string. The newline is technically a character, so stringLength counts it. Whether you want to count it depends on your application.
A version using the pointer-arithmetic form of the length function:
Variant: pointer-walk version
#include <stdio.h>
#include <stddef.h>
size_t stringLength(const char *s) {
const char *start = s;
while (*s != '\0') {
s++;
}
return (size_t)(s - start);
}
int main(void) {
char buffer[200];
printf("Enter a string: ");
if (!fgets(buffer, sizeof(buffer), stdin)) return 1;
printf("Length: %zu\n", stringLength(buffer));
return 0;
}
The cast (size_t)(s - start) is technically unnecessary on most platforms, since s - start is already a ptrdiff_t (a signed integer type) and the conversion to size_t is automatic. But the explicit cast documents the intent and silences warnings on some compilers. In modern C, you can use ptrdiff_t or size_t; both are fine here.
And a version that uses recursion, which is somewhat unusual but a good exercise:
Variant: recursive length
#include <stdio.h>
#include <stddef.h>
size_t stringLengthRec(const char *s) {
if (*s == '\0') return 0;
return 1 + stringLengthRec(s + 1);
}
int main(void) {
char buffer[200];
printf("Enter a string: ");
if (!fgets(buffer, sizeof(buffer), stdin)) return 1;
printf("Length: %zu\n", stringLengthRec(buffer));
return 0;
}
The recursion says: "if we're at the terminator, the length is 0; otherwise, it's 1 plus the length of the rest of the string." Elegant and correct — but not practical for long strings, because each recursive call uses a stack frame, and for a string of length n, you'd get n frames deep. For a 100,000-character string, that would overflow the stack. The iterative version is always preferred in real code. Still, the recursive one is a nice illustration of the recursive structure of "length."
Program Output
A typical run:
Enter a string: hello
Length (including newline): 6
Length (without newline): 5
The input "hello" is 5 characters, but fgets appends a newline, so the first length is 6. After stripping the newline, the second length is 5 — the true visible length of the word. This is a subtle but important point: what you consider "the length" depends on whether trailing whitespace counts.
With a string containing spaces:
Enter a string: Hello World
Length (including newline): 12
Length (without newline): 11
"Hello World" has 11 characters (including the space), plus the newline makes 12.
With an empty input (just pressing Enter):
Enter a string:
Length (including newline): 1
Length (without newline): 0
Just a newline character in the buffer: length 1 with it, 0 without. Correct in both cases.
And with a string that hits the buffer boundary (200 characters, so fgets reads 199 plus the terminator):
Enter a string: [200+ characters...]
Length (including newline): 199
Length (without newline): 199
When the input exceeds the buffer, fgets reads at most sizeof(buffer) - 1 characters (to leave room for the terminator), so the length caps at 199. No newline is stored because there wasn't room. This is a safe behavior — the function won't read past the buffer.
Step-by-Step Explanation
Let's walk through the length function and how it handles strings in memory.
1. The string in memory
When fgets reads "hello\n" into buffer, the array looks like this:
index: 0 1 2 3 4 5 6
value: 'h' 'e' 'l' 'l' 'o' '\n' '\0'
The visible content is 5 characters plus the newline, followed by the null terminator at index 6. The null terminator is what our function looks for — it marks the end.
2. The loop
while (s[count] != '\0') count++; — walk through the array, incrementing count on each iteration, until s[count] is the null terminator. For our example:
- count = 0, s[0] = 'h', not '\0', increment to 1.
- count = 1, s[1] = 'e', not '\0', increment to 2.
- count = 2, s[2] = 'l', not '\0', increment to 3.
- count = 3, s[3] = 'l', not '\0', increment to 4.
- count = 4, s[4] = 'o', not '\0', increment to 5.
- count = 5, s[5] = '\n', not '\0', increment to 6.
- count = 6, s[6] = '\0', loop ends.
Return 6 — the number of characters before the null terminator (5 visible characters plus the newline).
3. Why the null terminator matters
The null terminator is essential — it's what tells the function where the string ends. Without it, the loop would keep reading memory past the end of the string, potentially finding arbitrary bytes until it eventually (or never) hits a zero. That's the classic "off-by-one" or "buffer overrun" bug in C. The convention works only if every string is properly null-terminated, which is why C string functions always add a '\0' when they create or modify strings.
4. Why the length doesn't include the terminator
When strlen (and our function) returns "5" for "hello", it's counting the visible characters before the terminator, not the array's total capacity. The terminator is a sentinel — a marker, not a character. If you allocated a 200-byte buffer and stored "hello" in it, the array has 200 bytes, but the string's length is still 5. The function only cares about the content up to the terminator, not the array's size.
5. The size_t return type
size_t is an unsigned integer type defined in <stddef.h> (also pulled in by <stdio.h> and <string.h>). Its size is platform-dependent — typically 32-bit on 32-bit systems, 64-bit on 64-bit systems. It's chosen because it's guaranteed to be large enough to hold the size of any object, which means it can represent the length of any string you could possibly allocate. int would be too small on 64-bit systems for huge strings (and undefined behavior on negative lengths). Using size_t is the conventional choice for length functions, and it matches the library's strlen.
6. The %zu format specifier
printf("%zu", len) — the z modifier says "the argument is a size_t." This is essential for correct printing. If you use %d with a size_t on a 64-bit system, the format string tells printf to read 4 bytes but size_t is 8 bytes, causing garbage output. Always use %zu for size_t values. The same applies to ptrdiff_t (%td), intmax_t (%jd), and other size-related types.
7. The const qualifier
const char *s promises that the function won't modify the input. This has two benefits. First, it lets callers pass const strings (like string literals, or read-only buffers) without a warning. Second, it catches bugs — if you accidentally write s[0] = 'X' inside the function, the compiler errors. Making parameters const whenever possible is a good habit that improves both correctness and documentation.
8. Why not just use strlen?
In real code, you should — strlen is well-tested and highly optimized (modern implementations read multiple bytes at once, use SIMD instructions on some platforms, and are significantly faster than a byte-by-byte loop). But writing your own once teaches you what strlen does and why it's O(n). Every C programmer should write strlen, strcpy, and strcmp from scratch at least once. After that, use the library versions with confidence.
9. Complexity
The loop runs n iterations for a string of length n — O(n) time. Space usage is O(1) beyond the string itself — one counter, one pointer. There's no shortcut to finding the length, because C strings don't store it. If you find yourself calling strlen repeatedly in a tight loop, consider computing it once and saving the result — it's a common optimization.
10. Multi-byte characters
Our function counts bytes, not characters. For ASCII text, bytes and characters are the same. But for UTF-8 (the dominant encoding for non-ASCII text), a single character can be 2–4 bytes. So stringLength("café") would return 5 (c, a, f, é's 2 bytes), even though there are 4 visible characters. This is a known limitation of byte-oriented string handling. If you need to count characters (not bytes), you'd use a Unicode-aware library (like ICU) or write custom logic that decodes UTF-8. For teaching purposes, ASCII is assumed, and byte length is the standard answer.
🔍 Try this: run the program and enter a string of exactly 199 characters (which is the maximum fgets will read into a 200-byte buffer). Note that fgets doesn't include a newline, because it ran out of room. Then enter a string of 200+ characters — the function will read the first 199 and leave the rest in the input buffer. This is how fgets protects against buffer overruns, and it's worth understanding before you write your own input functions.
Frequently Asked Questions
1. Why not just use strlen()?
In production code, you should. strlen is well-tested and heavily optimized. But writing your own once is essential for understanding what strlen does and how C strings work. The exercise teaches you the loop, the null terminator, and the O(n) complexity. Once you've internalized those, use the library version — it's faster and cleaner.
2. Why is size_t better than int for the return type?
Because size_t is guaranteed to hold the size of any object, so it can represent the length of any string you could allocate. int's maximum (about 2.1 billion) is smaller than the maximum possible string size on 64-bit systems, and using int risks truncation for very large strings. Also, size_t is unsigned, which is semantically correct for a length — a length can never be negative. Most library functions (strlen, sizeof, malloc) use size_t, so matching the convention keeps your code compatible with the standard library.
3. What happens if the string isn't null-terminated?
Undefined behavior. The function will keep incrementing count and reading s[count] past the end of the string, into whatever memory happens to be adjacent. This could read garbage bytes (returning a very large number), or crash with a segmentation fault if it reads into unmapped memory, or (rarely) run forever if the memory never contains a zero. This is why every C string must be properly null-terminated, and why functions that create strings (strcpy, sprintf, snprintf) always write the terminator.
4. Is the newline at the end of fgets input part of the length?
Technically yes — fgets stores the newline as a character in the buffer, so strlen (and our function) count it. Practically, most programs don't want the newline, so they strip it after reading. Our program does this by finding the '\n' and replacing it with '\0', then recounting. The two lengths reported in the output (with and without the newline) show both interpretations, so you can see the difference.
5. How does strlen handle multi-byte characters?
It doesn't — strlen counts bytes, not characters. For UTF-8, a character like "é" is 2 bytes, so strlen("café") returns 5, not 4. Similarly, an emoji might be 4 bytes, so a string with one emoji and 3 letters has strlen of 7, not 4. If you need character counts (not byte counts), you'd need a Unicode-aware library. For most C programs, byte length is the standard — it's what malloc needs, and it's what the rest of the string functions use. Just be aware of the distinction when working with internationalized text.
6. Can I optimize stringLength to be faster?
Yes. The classic optimization is to read 4 or 8 bytes at a time (as a uint32_t or uint64_t) and check whether any byte is zero using bit tricks ((x - 0x01010101) & ~x & 0x80808080 for 32-bit words). This can be 4–8× faster than a byte-by-byte loop. The standard library versions do this, plus SIMD versions on modern CPUs. For teaching purposes, byte-by-byte is fine. For production, use strlen. The speedup matters mainly when you're calling strlen on very large strings in tight loops — a case that's become rare as modern codebases tend to track lengths separately.
💡 Tip: Once this works, write stringConcat, stringCopy, and stringCompare — the three other core string functions. They all use the same pattern: loop until the null terminator, doing something at each character. Once you've written them all, you'll understand how the entire <string.h> library works under the hood. That's a level of understanding that most C programmers never quite reach, but it makes every string-related bug much easier to diagnose.