Characters, buffers, and strings
Understand termination, capacity, length, literals, copies, and why text-handling functions need explicit contracts.
In this chapter9 sections
A buffer gives us storage. A C string needs stored characters and a terminating null character. Separating storage capacity from string length explains many common copying and input mistakes. Include <string.h> for the string functions used here.
1. A string needs a terminating null character
A C string is a sequence of characters ending at and including its first null character. The string length counts the C bytes (char elements) before that terminator. '\0' is a character constant with value zero; it is not the digit character '0', and it is not a null pointer. In these ordinary char examples, each array element occupies one C byte.
- index 0'C'
- index 1'a'
- index 2't'
- index 3'\0'
char message[] = "Cat";
size_t capacity = sizeof message;
size_t length = strlen(message);
char raw[3] = {'C', 'a', 't'} is a valid character array, but it has no terminator and is not a C string. Passing it to strlen or to a plain %s conversion would require reading beyond its valid string data. The called function cannot infer missing capacity or invent a safe stopping point.
2. Capacity and length answer different questions
Capacity describes the available storage under an interface’s contract. Length describes the data currently present. For a valid string stored entirely in a character array, there must be space for the length plus one terminating element. A larger buffer may contain a shorter string; unused capacity does not become part of that string’s length.
char data[] = {'A', '\0', 'B', '\0'};
The first zero ends the first string; the later B remains stored data. sizeof measures this complete array’s storage and does not scan for a terminator. strlen scans a valid string and returns a size_t length. Using sizeof on a pointer gives pointer size, so it cannot recover a buffer’s allocation size or its string length.
3. A literal and a writable copy have different rules
const char *view = "Cat";
char editable[] = "Cat";
editable[0] = 'B';
An ordinary string literal supplies an array with static storage duration. Trying to modify that literal is undefined behavior, whether or not a particular machine places it in read-only storage. const char *view communicates read-only access through the pointer. char editable[] creates a separate writable array initialized from the literal, including the terminator.
Use strcmp for the usual lexicographic comparison of valid strings. Pointer equality asks whether pointer values compare equal, not whether two sequences spell the same text. strcmp promises a negative, zero, or positive result; it does not promise exactly -1 or 1 for unequal strings.
4. A copy must respect both regions
char source[] = "Cat";
char destination[sizeof source];
memcpy(destination, source, sizeof source);
This known-size example copies the terminator too, into a large enough separate destination. memcpy copies a byte count, not an abstract string; both regions must be valid for that count and must not overlap. The count is deliberately computed from the actual source array, not a source pointer or guessed text length.
char word[] = "abcd";
memmove(word + 1, word, 3);
word[4] = '\0';
memmove supports overlap, behaving as though the source bytes were first copied through a temporary array. It still needs valid ranges. Neither function adds a terminator automatically. The shifted example explicitly keeps one in bounds. For input of unknown length, first establish capacity, a size limit, and how truncation or failure is reported.
5. A bounded-looking name is not a full contract
strcpy needs enough destination room for the complete source string and terminator. strncpy can leave the destination unterminated when the source has at least the given count; for shorter sources it pads the remaining count with null characters. It is not a general drop-in safe string copy. strncat limits appended characters, not total destination capacity. snprintf can bound formatted output, but its return value must still be checked for errors and truncation.
Finally, a byte length is not always a human-perceived character count. In a UTF-8 environment, one visible character can use multiple bytes, and a displayed symbol can involve multiple code points. Ordinary strlen does not parse those text rules. C23 adds facilities, but ordinary narrow-string storage still requires deliberate choices about encoding, capacity, and termination.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.4.5, 6.7.9, 7.1.1, 7.21.6.1, 7.24.2–7.24.6. These stable rules support the C17 baseline; this draft is not the final ISO publication.
Next, Text, Unicode, UTF-8, and locale separates stored units from code points and displayed characters.
Optional visual model: Find where a string ends
Find where a string ends
VISUAL MODEL
Keep the array size fixed and move the first null character. Watch the string length change.
These fragments are inside a function with <string.h> included. Both choices use three basic execution characters.
char text[6] = "cat";size_t before = strlen(text);text[1] = '\0';size_t after = strlen(text);
text[0]—Initializer not reachedtext[1]—Initializer not reachedtext[2]—Initializer not reachedtext[3]—Initializer not reachedtext[4]—Initializer not reachedtext[5]—Initializer not reached- Array capacity
- 6
- strlen result in this step
- —
The initializer has not been reached. The declared capacity is six char elements.
Capacity counts all array elements. strlen counts characters before the first null character, excluding that terminator. Later bytes are not erased by an earlier terminator.
Read the complete trace
- The initializer has not been reached. The declared capacity is six char elements.
- The literal initializes three letters and a null. The remaining two elements are also zero-initialized.
- strlen(text) is 3. Capacity remains 6. The first null is at index 3.
- Writing a null at index 1 creates an earlier terminator. The later elements keep their stored characters.
- strlen(text) is now 1. The array still has six elements; length and capacity are different facts.
Before you move on
- A C string ends at its first null character and needs storage for that terminator.
- Capacity measures available storage; strlen measures units before the terminator in a valid string.
- Copies require valid regions, enough space, and the operation’s overlap contract.
Keep these ideas separate
- Character array / C string
- An array of characters can lack a terminator and therefore fail to provide a valid C string.
What must be true before a string function can safely scan a character buffer?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Capacity 3, length 6.
This reverses the array’s element count and the character count before the first null.
- Capacity 6, length 3.
✓ Correct reasoning. The array has six elements; strlen excludes the terminating null and stops before it.
- Capacity 6, length 6.
Extra zero-initialized elements do not extend the string past its first null.
C17
Ready for the next idea?
Mark this chapter as read whenever you feel ready.