YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Memory & dataChapter 26 of 73

Characters, buffers, and strings

Understand termination, capacity, length, literals, copies, and why text-handling functions need explicit contracts.

6 min readFoundationsC17 baseline
Offline reading
In this chapter9 sections
0% through this chapter

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.

  1. index 0'C'
  2. index 1'a'
  3. index 2't'
  4. index 3'\0'
Four char elements: three letters and the terminator. Each element is one C byte; this is not a Unicode character-counting model.
C17 · illustrative fragment
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.

C17 · illustrative fragment
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

C17 · illustrative fragment
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

C17 · illustrative fragment
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.

C17 · illustrative fragment
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

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.

  1. char text[6] = "cat";
  2. size_t before = strlen(text);
  3. text[1] = '\0';
  4. size_t after = strlen(text);
chartext[0]—Initializer not reached
chartext[1]—Initializer not reached
chartext[2]—Initializer not reached
chartext[3]—Initializer not reached
chartext[4]—Initializer not reached
chartext[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
  1. The initializer has not been reached. The declared capacity is six char elements.
  2. The literal initializes three letters and a null. The remaining two elements are also zero-initialized.
  3. strlen(text) is 3. Capacity remains 6. The first null is at index 3.
  4. Writing a null at index 1 creates an earlier terminator. The later elements keep their stored characters.
  5. 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.
Explain it in your own words

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.

char text[6] = "cat"; What are its capacity and strlen result?
Read the explanation for every choice
  1. Capacity 3, length 6.

    This reverses the array’s element count and the character count before the first null.

  2. Capacity 6, length 3.

    ✓ Correct reasoning. The array has six elements; strlen excludes the terminating null and stops before it.

  3. 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.

CHAPTER 26 / 73

In this chapter

Characters, buffers, and strings

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping