Thuta Learning
C
IntermediateProgrammingBeginner

Strings

CLesson 1730 min

What you'll walk away with

  • Draw a string in memory, including its '\0' terminator
  • Tell strlen (length) from sizeof (capacity) and size buffers with room for '\0'
  • Copy with snprintf instead of strcpy, strcat or gets, and detect truncation from its return value
  • Compare strings with strcmp, not ==
  • Explain why strlen counts bytes, not characters, in UTF-8 text

Explain it simply

Explain it simply

C has no dedicated string type. Text is stored as a row of chars in an array, followed by a "the text ends here" marker: '\0', a byte whose value is 0. Picture a train: one carriage per letter, plus a final marker carriage at the end.

Functions such as printf and strlen walk forward until they meet that marker. The two big ideas of this lesson follow from it: the array must always keep one byte for the marker, and the array's size is not the same as the text's length.

Problem → Why → Solution

The problem: a copy that writes more than fits

You copy a company name into char name[8] with strcpy(). "Thuta Technology" is 16 characters, 17 bytes with its '\0', but the buffer holds only 8. strcpy never asks how big the destination is, so it writes the remaining 9 bytes over whatever memory follows the array.

overflow.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[8];                        /* room for 7 chars + '\0' */
    strcpy(name, "Thuta Technology");    /* 17 bytes into 8: overflow */
    printf("%s\n", name);
    return 0;
}

Why is this dangerous?

strcpy copies until it reaches the source's '\0' and knows nothing about the destination's capacity. Writing past the array is undefined behaviour, and this is the classic buffer overflow behind many security holes. Because the source here is a literal, GCC can spot it even without flags: "'__builtin_memcpy' writing 17 bytes into a region of size 8 overflows the destination [-Wstringop-overflow=]". When the text arrives from a user or a file at run time, no compiler can see its length, and there is no warning at all.

Core concept: terminator, capacity and length

A C string is a sequence of char values ending with the null character '\0'. The terminator is the only thing that marks where the text ends: printf("%s"), strlen() and every other string function walk forward byte by byte until they find it. char name[] = "ThutaTech"; creates an array of 10 chars: the 9 letters plus the '\0' the compiler adds after every string literal.

So every string has two different sizes. Its capacity is how many bytes the array can hold, which sizeof reports while the array is in scope: sizeof name is 10. Its length is how many characters come before the terminator, which strlen() counts at run time: strlen(name) is 9. A buffer of N bytes can hold at most N - 1 characters, because one byte is reserved for '\0'. strlen() returns size_t, so print it with %zu.

Because strings are arrays, the array rules from the previous lesson apply. You cannot assign with = (name = "Aye"; is a compile error) or compare with ==: answer == "yes" compares two addresses, and GCC's -Wall warns that the result is unspecified. Use strcmp(a, b), which returns 0 when the contents are equal, a negative number when a sorts first and a positive number when b does. A string literal itself lives in memory you must not modify: char *p = "hello"; p[0] = 'H'; is undefined behaviour and crashes on many systems, so point at literals with const char *.

Functions that write into a buffer need to know its capacity. strcpy(), strcat() and sprintf() do not take one, which is how buffer overflows happen, and gets(), which read a line with no limit at all, was removed from the language in C11. Prefer snprintf(dest, sizeof dest, ...): it never writes more than the given size, always adds '\0' when the size is above 0, and returns the length it wanted to write, so a return value >= sizeof dest tells you the text was cut.

text
char name[] = "ThutaTech";
--------------------------
  index:  0   1   2   3   4   5   6   7   8   9
        +---+---+---+---+---+---+---+---+---+----+
        | T | h | u | t | a | T | e | c | h | \0 |
        +---+---+---+---+---+---+---+---+---+----+
        <--------- strlen(name) = 9 -------->
        <------------ sizeof name = 10 ----------->
Mental model: text, then '\0', then spare room
  1. A string is chars ending in '\0'
  2. strlen counts up to the '\0'
  3. sizeof = capacity (array in scope)
  4. Writes need the capacity: snprintf

Capacity must be at least length + 1; that extra byte is where the '\0' lives.

General pattern

c
char buffer[CAPACITY] = "text";     /* CAPACITY > strlen("text") */
const char *label = "read-only literal";

size_t length = strlen(buffer);     /* chars before '\0' */
int needed = snprintf(buffer, sizeof buffer, "%s", source);
if (needed >= (int)sizeof buffer) { /* the copy was cut short */ }

if (strcmp(first, second) == 0) {   /* same contents */
    statements;
}

Use a char array for strings you will change and const char * for literals you will not. Call snprintf with the buffer and sizeof buffer, and check its return value. Compare contents with strcmp(...) == 0.

Example: length, capacity and a safe format

This program shows the two sizes of one string, writes safely into a buffer with snprintf, and finally reports the byte count of a Myanmar word. It prints the count rather than the Myanmar text itself, so the output is the same in every terminal.

strings.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char name[] = "ThutaTech";            /* 9 letters + '\0' = 10 bytes */

    printf("Name: %s\n", name);
    printf("strlen: %zu\n", strlen(name)); /* characters before '\0' */
    printf("sizeof: %zu\n", sizeof name);  /* bytes in the whole array */

    char greeting[32];
    snprintf(greeting, sizeof greeting, "Hello, %s!", name);
    printf("%s (%zu chars)\n", greeting, strlen(greeting));

    const char *word = "မင်္ဂလာပါ";       /* UTF-8 Myanmar text */
    printf("Myanmar word: %zu bytes\n", strlen(word));
    return 0;
}

Code breakdown

  1. The hidden terminatorchar name[] = "ThutaTech"; /* 9 letters + '\0' = 10 bytes */

    With no size given, the compiler counts the literal, adds one byte for the '\0' and creates a char[10].

  2. Lengthprintf("strlen: %zu\n", strlen(name)); /* characters before '\0' */

    strlen counts from name[0] until it meets the '\0' and does not count the terminator, giving 9. It returns size_t, hence %zu.

  3. Capacityprintf("sizeof: %zu\n", sizeof name); /* bytes in the whole array */

    sizeof gives the whole array's byte count, 10, at compile time. If name were a char * pointer, it would give the pointer's size instead.

  4. Bounded writesnprintf(greeting, sizeof greeting, "Hello, %s!", name);

    "Hello, ThutaTech!" is 17 characters, 18 bytes with '\0', so it fits in 32 bytes. Had name been longer, snprintf would write at most 31 characters and still end with '\0'.

  5. Bytes, not lettersprintf("Myanmar word: %zu bytes\n", strlen(word));

    မင်္ဂလာပါ is written with 9 code points, and every Myanmar code point takes 3 bytes in UTF-8, so strlen returns 27. strlen knows nothing about encodings; it only counts the bytes before '\0'.

You should see
Name: ThutaTech
strlen: 9
sizeof: 10
Hello, ThutaTech! (17 chars)
Myanmar word: 27 bytes

Copying and joining without overflowing

The code below copies two sources into char small[8] with snprintf. "Thuta" fits; "Thuta Technology" is cut, and the return value 16, larger than the buffer size 8, reveals the truncation. The second part calls strncat with the space that is left (sizeof path - strlen(path) - 1), because strncat's n is the maximum number of characters to append, not the buffer size.

safe_copy.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *sources[] = {"Thuta", "Thuta Technology"};

    for (size_t i = 0; i < 2; i++) {
        char small[8];
        int needed = snprintf(small, sizeof small, "%s", sources[i]);

        printf("copied \"%s\"", small);
        if (needed >= (int)sizeof small) {
            printf(" (truncated: needed %d chars, room for %zu)",
                   needed, sizeof small - 1);
        }
        printf("\n");
    }

    char path[16] = "docs";
    strncat(path, "/lessons/c/strings", sizeof path - strlen(path) - 1);
    printf("path: \"%s\" (%zu chars)\n", path, strlen(path));
    return 0;
}

strncpy does not always add '\0'

strncpy(dest, src, sizeof dest) looks safe, but when src is longer than dest it stops without writing '\0'. dest is then not a string, and the next strlen or printf reads past the end of the buffer. snprintf is the simpler choice for copying.

Comparing strings

strcmp() compares two strings character by character up to the '\0'. Rely only on the sign of the result: the standard promises zero, negative or positive, not exactly -1 or 1.

compare.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char answer[] = "yes";

    printf("strcmp(answer, \"yes\") = %d\n", strcmp(answer, "yes"));
    printf("apple sorts first: %d\n", strcmp("apple", "banana") < 0);

    if (strcmp(answer, "yes") == 0) {
        printf("The answer is yes\n");
    }
    return 0;
}

UTF-8 and Myanmar text

In UTF-8 an English letter takes 1 byte, but every Myanmar code point takes 3. So buffers for Myanmar text must be sized in bytes, and cutting text at an arbitrary byte, for example when snprintf can fit only 7 bytes into a char[8], can leave half a character at the end: broken UTF-8.

TextCode pointsstrlen (bytes)
C11
ThutaTech99
မ13
မင်္ဂလာပါ927

In real projects

Where this shows up in real projects

Text handling is where C programs most often go wrong, so mature codebases settle on a few rules. Every buffer that receives text travels with its capacity: fgets(buf, sizeof buf, stdin), snprintf(buf, sizeof buf, ...). Input from users, files or the network is checked for length and for a missing newline: fgets stores the newline when the line fits and leaves it out when the line was too long, which is how truncation is detected, and buf[strcspn(buf, "\n")] = '\0'; trims it.

Log messages, file paths and HTTP headers are built with snprintf and its return value is checked. Many projects ban strcpy, strcat, sprintf and gets outright through their style guide or lint rules. For Myanmar and other non-Latin text, programs store UTF-8, size buffers in bytes, and use a Unicode library such as ICU when they need to count or cut the characters a user actually sees.

Common mistakes

Common mistakes

1. No room for the '\0'

char code[3] = "abc"; is valid C, but there is no terminator, so it is not a string, and printf("%s") or strlen will read past the end of the array. GCC with -Wextra warns: "initializer-string for array of 'char' truncates NUL terminator". Leave the size out (char code[] = "abc";) or use length + 1.

2. Comparing strings with ==

if (answer == "yes") compares two addresses, not the contents, so it can be false even when the user typed yes. GCC's -Wall says "comparison with string literal results in unspecified behavior". Use strcmp(answer, "yes") == 0.

3. Copying with functions that take no capacity

strcpy, strcat and sprintf do not know the destination size, so one long input causes an overflow, and strncpy can leave the result without '\0'. Use snprintf(dest, sizeof dest, "%s", src) and check its return value.

4. Using sizeof on a char * to get the length

With const char *word = "hello";, sizeof word is not 5 but the size of a pointer, typically 8 on 64-bit systems. Always use strlen for the length, and keep sizeof for the capacity of an actual array.

5. Modifying a string literal

char *p = "hello"; p[0] = 'H'; is undefined behaviour, and because literals usually sit in read-only memory it crashes on many systems. If you need to change the text, create an array copy: char word[] = "hello";.

Mini challenge

Mini challenge: building usernames

Build "first.last" usernames from two pairs of names into a char user[16] buffer with snprintf. Print each username with its length, and mark it when it was truncated or when it matches a name that is already taken.

  • Use firsts = {"aung", "thiri"}, lasts = {"kyaw", "aungsoemoe"} and taken = "aung.kyaw"
  • Call snprintf with user and sizeof user, and keep its return value
  • Print the username and its strlen as "name (N chars)"
  • Add " [truncated from N]" when the return value is >= sizeof user
  • Add " [taken]" when strcmp says the username equals taken
usernames.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *firsts[] = {"aung", "thiri"};
    const char *lasts[] = {"kyaw", "aungsoemoe"};
    const char *taken = "aung.kyaw";

    // TODO: loop over both name pairs (index 0 and 1)
    //   TODO: char user[16]; build "first.last" with snprintf, keep the return value
    //   TODO: print the username and its strlen
    //   TODO: print " [truncated from N]" when the return value shows truncation
    //   TODO: print " [taken]" when strcmp says user equals taken
    //   TODO: end the line
    return 0;
}

Expected: The program prints these two lines: aung.kyaw (9 chars) [taken] thiri.aungsoemo (15 chars) [truncated from 16]

Show hint

The format is "%s.%s" with two arguments. The return value is an int and sizeof gives a size_t, so compare against (int)sizeof user to avoid a sign-compare warning. "thiri.aungsoemoe" is 16 characters, which leaves no room for '\0' in a 16-byte buffer.

Show solution
usernames.c
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *firsts[] = {"aung", "thiri"};
    const char *lasts[] = {"kyaw", "aungsoemoe"};
    const char *taken = "aung.kyaw";

    for (size_t i = 0; i < 2; i++) {
        char user[16];
        int needed = snprintf(user, sizeof user, "%s.%s", firsts[i], lasts[i]);

        printf("%s (%zu chars)", user, strlen(user));
        if (needed >= (int)sizeof user) {
            printf(" [truncated from %d]", needed);
        }
        if (strcmp(user, taken) == 0) {
            printf(" [taken]");
        }
        printf("\n");
    }
    return 0;
}

Quick quiz 1 / 3

Given char word[] = "C17";, what are sizeof word and strlen(word)?

Quick quiz 2 / 3

With char buf[16];, which line safely copies a string src of unknown length into buf?

Quick quiz 3 / 3

In char answer[] = "yes"; if (answer == "yes") ..., what does == compare?

What to remember

  • A C string is a char array ending in '\0'; an N-byte buffer holds at most N - 1 characters.
  • strlen counts the bytes before '\0'; sizeof gives an array's capacity (not through a pointer).
  • Copy and format with snprintf(dest, sizeof dest, ...) and check its return value; gets was removed in C11.
  • Compare contents with strcmp(...) == 0; == compares addresses.
  • In UTF-8 each Myanmar code point is 3 bytes, so strlen counts bytes and buffers are sized in bytes.

SEI CERT C Coding Standard — Carnegie Mellon SEI

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Strings | Thuta Learning