Sub topic 9
Strings and the Null Terminator
Prerequisites and the basic model
Assume you know C arrays, pointers, pointer arithmetic, and functions. In C, a string is a sequence of char values that ends with a null terminator. The null terminator is the byte '\0', whose numeric value is zero.
The terminator is not the same as the character '0'. The character '0' is printable. The character '\0' marks the end of a string.
#include <stdio.h>
#include <string.h>
int main(void) {
char word[6] = "hello";
printf("%s\n", word);
printf("%zu\n", strlen(word));
printf("%zu\n", sizeof word);
return 0;
}The array has six elements: five letters and one '\0'. Therefore, strlen(word) returns 5, while sizeof word returns 6. strlen counts characters before the terminator. sizeof reports the array's storage size in bytes.
Walking through a string
A string can be processed by moving a pointer until it points to '\0'.
#include <stddef.h>
#include <stdio.h>
size_t my_strlen(const char *s) {
const char *p = s;
while (*p != '\0') {
p++;
}
return (size_t)(p - s);
}
int main(void) {
char text[] = "GATE";
printf("%zu\n", my_strlen(text));
return 0;
}The expression *p reads the character at the current position. Pointer subtraction gives the number of char elements between the two positions. Since p stops at the terminator, the result is the string length.
Arrays, pointers, and capacity
A string literal used to initialize an array supplies the terminator automatically:
char a[] = "cat";This creates four elements: c, a, t, and '\0'.
However, a character array is not automatically a valid string:
char bad[3] = {'c', 'a', 't'};There is no room for '\0'. Passing bad to %s, strlen, or another string function can read beyond the array, causing undefined behavior.
When a string is passed to a function, the array usually decays to a pointer. Thus, inside the function, sizeof cannot determine the original array's capacity.
>callout note Always reserve one byte for '\0'. A buffer that stores at most n visible characters needs capacity for at least n + 1 characters.
GATE traps
| Expression | Meaning |
|---|---|
| `strlen(s)` | Number of characters before `'\0'` |
| `sizeof s` for an array | Total array storage in bytes |
| `sizeof s` for a pointer | Pointer size, not string length |
Exercise
What does this print: char s[] = "abc"; printf("%zu %zu", strlen(s), sizeof s);?
Show answer
It prints 3 4, because the array contains three letters and one null terminator.