Sub topic 9
Strings and the null terminator
This chapter assumes you know pointer arithmetic, array decay, and the *p++ precedence rules from the earlier chapters. C has no string type. A string is a convention: a sequence of char values in consecutive memory, ended by a byte with value 0. Almost every string question in GATE reduces to knowing where that zero byte is.
What a string is
The terminating byte is the null terminator, written '\0'. It is not the character '0', which has ASCII code 48. The literal "hi" occupies 3 bytes: 'h', 'i', '\0'.
Library functions such as strlen, printf("%s"), and strcpy scan forward until they find that zero byte. They never know the buffer's real size. If the terminator is missing, they read past the end, which is undefined behavior.
Array versus pointer initialization
Two declarations look alike but behave differently.
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "hello";
const char *p = "hello";
printf("%zu %zu\n", sizeof a, strlen(a));
printf("%zu %zu\n", sizeof p, strlen(p));
a[0] = 'j';
printf("%s\n", a);
return 0;
}On a typical 64-bit system the output is:
6 5
8 5
jellochar a[] = "hello"creates an array of 6 bytes and copies the literal into it. The array is yours to modify, andsizeof ais 6.const char *p = "hello"creates a pointer to a string literal.sizeof pis the size of a pointer, and the output shows 8 on a 64-bit system. Modifyingp[0]is undefined behavior, because literals may live in read-only memory.
| Expression | Value for `"hello"` | Why |
|---|---|---|
| `sizeof a` (array) | 6 | Counts the terminator |
| `strlen(a)` | 5 | Counts bytes before the terminator |
| `sizeof p` (pointer) | pointer size | Size of the pointer, not the string |
| `sizeof "hello"` | 6 | A literal is a `char[6]` |
Computing the length
strlen walks a pointer until it reaches the terminator. The distance covered is the length.
#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) {
printf("%zu\n", my_strlen("GATE"));
return 0;
}This prints 4. The loop condition *p != '\0' is usually shortened to *p, since a zero byte is false.
Copying with the classic idiom
#include <stdio.h>
void my_strcpy(char *d, const char *s) {
while ((*d++ = *s++) != '\0') {
;
}
}
int main(void) {
char buf[8];
my_strcpy(buf, "cat");
printf("%s\n", buf);
return 0;
}This prints cat. In *d++ = *s++, each ++ has higher precedence than *, and each returns the old pointer value. So the loop reads the byte at s, stores it at d, advances both pointers, and then tests the stored value. The terminator is copied and then ends the loop, so the copy is itself a valid string.
The function trusts the caller. If buf were 3 bytes, the copy would write the terminator out of bounds.
Embedded zeros and partial initialization
The terminator is only a convention. A zero byte inside the data ends the string early for every library function.
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "ab\0cd";
printf("%zu %zu\n", sizeof s, strlen(s));
printf("%s\n", s);
return 0;
}The output is 6 2 and then ab. The array holds a, b, \0, c, d, and the automatic terminator, so sizeof gives 6. strlen and printf stop at the first zero.
Some initialization rules appear in exam questions:
char s[5] = "ab";storesa,b, and three zero bytes. Missing elements are zero-filled.char s[3] = "abc";is valid C. It fills the array exactly and leaves no terminator, sostrlen(s)is undefined behavior. (C++ rejects this declaration.)char s[2] = "abc";is a constraint violation, because the literal has more characters than the array can hold.char s[] = {'a', 'b'};is not a string, since no terminator is stored.
Traps that GATE likes
Comparing with ==. For char * operands, == compares addresses, not contents. Use strcmp, which returns 0 when the strings are equal. A nonzero result means they differ, so if (strcmp(a, b)) is true for unequal strings.
Unsigned subtraction. strlen returns size_t, an unsigned type. The expression strlen(a) - strlen(b) >= 0 is always true. If a is shorter, the subtraction wraps to a huge positive number, not a negative one.
Character literals have type int. In C, sizeof 'a' equals sizeof(int), usually 4. In C++ it is 1.
'\0', '0', and "0" differ. The value '\0' is the integer 0. The value '0' is the integer 48. The literal "0" is a two-byte array, '0' followed by '\0'.
Concatenation needs room. strcat(d, s) finds the terminator of d and appends there. The destination must already hold strlen(d) + strlen(s) + 1 bytes.
Strings as function parameters
An array of char decays to char * when passed to a function. Inside the function, sizeof s is the pointer size, not the buffer size. This is the same decay you saw earlier. It is why string functions rely on the terminator and not on a length.
Pointer-walking patterns
The following loop counts occurrences of a character:
#include <stdio.h>
int count_char(const char *s, char c) {
int n = 0;
for (; *s; s++) {
if (*s == c) {
n++;
}
}
return n;
}
int main(void) {
printf("%d\n", count_char("banana", 'a'));
return 0;
}It prints 3. Because s is a local copy of the pointer, advancing it does not affect the caller's pointer.
Exercise
What does this program print on a system where sizeof(int) is 4? char s[] = "GATE\0CS"; printf("%zu %zu %d", sizeof s, strlen(s), (int)sizeof 'G');
Show answer
It prints "8 4 4". The array holds G, A, T, E, a zero byte, C, S, and the automatic terminator, which is 8 bytes. strlen stops at the first zero byte and returns 4. A character literal such as 'G' has type int in C, so its size is 4.
Exercise
Let char a[] = "abcd"; and char b[] = "ab";. Does strlen(b) - strlen(a) < 0 evaluate to true? Explain.
Show answer
No. strlen returns the unsigned type size_t. The subtraction 2 - 4 wraps around to a very large positive number, so the comparison "< 0" is false. An unsigned value is never less than 0.