Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 171 ยท Strings

C-Style Strings and Character Arrays

Understand C-style strings in C++ - char arrays, the null terminator, strlen, strcpy, strcmp and snprintf, buffer overflows, and converting to and from std::string.

Before std::string existed, text in C and early C++ was just an array of char with a special character, '\0', marking the end. These C-style strings (also called null-terminated strings or C strings) never went away. Every string literal you write is one. Operating-system APIs, C libraries such as SQLite or OpenSSL, main's command-line arguments and countless older C++ code bases all speak this format.

You won't build new programs out of C strings, but you must be able to read them, pass them to C functions correctly and spot the bugs they invite. In this lesson you'll learn how character arrays and the null terminator work, the essential <cstring> functions (strlen, strcpy, strcmp and friends), why buffer overflows are so dangerous, and how to move text safely between C strings and std::string.

Character arrays and the null terminator

A C string is a sequence of characters followed by a null character, '\0' (the character with code 0). The terminator isn't part of the text, but it must be there: it's the only way C functions know where the string ends. Nothing stores the length.

TEXT
char word[] = "code";

index:   0    1    2    3    4
       +----+----+----+----+----+
       | c  | o  | d  | e  | \0 |
       +----+----+----+----+----+

That's why "code" needs five bytes: four letters plus the terminator.

C++ Arrays, literals and the terminator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Two different numbers describe a character array, and confusing them is a classic bug:

  • sizeof is the size of the array in bytes, fixed at compile time and including the terminator and any unused space.
  • std::strlen counts characters up to the first '\0'. It walks the array every time you call it, so it costs O(n).

std::println (and std::format) can print character arrays and const char* directly. They stop at the terminator, just like C functions do. The loop in the example uses the {:?} debug format, which shows the terminator explicitly as '\u{0}', the character with code 0.

String literals are const arrays

A literal like "hello" has the type const char[6]: an array of six constant characters with static storage, meaning it lives for the whole program. Two rules follow:

  • You can't modify a literal. char* p = "hello"; is an error in modern C++ (it was allowed with a warning in C++03). Write const char* p = "hello"; to point at a literal, or char buffer[] = "hello"; to get your own modifiable copy.
  • A pointer to a literal never dangles, because the literal is never destroyed.

When you pass an array to a function, or assign it to a pointer, it decays into a pointer to its first element. The function then has no idea how big the array was, which is why C functions take a separate size argument whenever they write into a buffer. C-Style Arrays and Pointers and Arrays cover decay in depth.

The <cstring> toolkit

The header <cstring> provides the C string functions in namespace std. These are the ones you'll meet most:

Function What it does Watch out
strlen(s) number of characters before '\0' O(n) each call; s must be terminated
strcpy(dst, src) copy src (with '\0') into dst no size check: overflows if dst is too small
strncpy(dst, src, n) copy at most n characters does not add '\0' if src is too long
strcat(dst, src) append src to the end of dst no size check
strcmp(a, b) compare: < 0, 0, or > 0 returns 0 when equal
strncmp(a, b, n) compare at most n characters
strchr(s, c) / strrchr(s, c) pointer to first / last c, or nullptr
strstr(s, sub) pointer to first occurrence of sub, or nullptr
memcpy, memset, memcmp work on raw bytes with an explicit count ignore '\0' entirely
C++ strlen, strcmp, strchr and strstr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The sign of strcmp's result is all that's guaranteed. Don't test for -1 or 1; test < 0, == 0 or > 0. And note the inversion: if (std::strcmp(a, b)) means "if they are different", which trips up nearly everyone once.

Comparing with == compares addresses

With std::string, a == b compares the text. With C strings it compares two pointers, which is almost never what you want:

C++ == compares pointers, not text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC warns about many of these mistakes when it can see them (-Waddress for comparing with a literal, -Warray-compare for comparing two arrays directly), but through pointers it can't. When in doubt, wrap the text in a std::string_view and compare views: std::string_view{p} == q compares characters.

Buffer overflows: why C strings are dangerous

strcpy and strcat write until they reach the source's terminator. They don't know how big the destination is. If the source is longer than the space, they keep writing past the end of the array into whatever memory comes next. That's a buffer overflow, it's undefined behavior, and it has been one of the most exploited security bugs in history: an attacker who controls the input can overwrite return addresses and take over the program.

C++
char name[8];
std::strcpy(name, "Bartholomew");   // 12 bytes into an 8-byte array: UNDEFINED BEHAVIOR

char greeting[16] = "Hello, ";
std::strcat(greeting, "wonderful world");   // 7 + 15 + 1 = 23 bytes: overflow

GCC catches some cases at compile time when the sizes are visible (-Wstringop-overflow), and -D_FORTIFY_SOURCE or AddressSanitizer (-fsanitize=address) catch many at runtime. None of them catch everything.

strncpy sounds like the fix, but it has its own trap: when the source is at least n characters long, it copies exactly n characters and doesn't add a terminator. The result isn't a valid C string, and the next strlen reads off the end.

The safest C tool for writing into a fixed buffer is std::snprintf (header <cstdio>). It never writes more than the size you give, always terminates the result (when the size is at least 1), and returns the length the full text would have had, so you can detect truncation.

C++ Safe writing with snprintf, and strncpy's trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The full text user-42-admin needs 13 characters plus a terminator, so snprintf keeps the first 11, terminates, and returns 13. Because every value here is a constant, GCC even spots the truncation while compiling and prints a -Wformat-truncation warning above the output. With real runtime data it can't, which is why you check the return value.

The manual code[sizeof code - 1] = '\0' line is the price of using strncpy: forget it once and you have a bug that may only show up in production. In C++, the better answer is usually not to manage the buffer at all.

Never read user input into a fixed char array with functions that don't take a size, like the old gets (removed from both languages) or std::cin >> buffer with a plain array before C++20. Read into a std::string with std::getline, which grows as needed (see Reading User Input).

Converting between C strings and std::string

Moving text across the boundary is easy once you know which direction owns what.

C string โ†’ std::string: construct or assign. The characters are copied up to the terminator. To copy a buffer that isn't terminated, or contains embedded '\0' bytes, pass a pointer and a length.

std::string โ†’ C string: call c_str() (or data()). The pointer belongs to the string and is valid only until the string is modified or destroyed, as the String Methods lesson explains.

std::string โ†’ your own char buffer: when a C API wants you to fill in a buffer, copy with a length check.

C++ Crossing the boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

printf's %zu is the specifier for std::size_t. The c_log function stands in for any C API: the important part is that s.c_str() is called right where it's needed and the string isn't changed while C code holds the pointer.

Command-line arguments

The most common place you'll see C strings in a modern program is main itself. Its full signature receives the arguments as an array of C strings:

C++
int main(int argc, char* argv[]) {
    // argv[0] is the program name, argv[1] .. argv[argc - 1] are the arguments
    for (int i = 1; i < argc; ++i) {
        std::string_view arg = argv[i];       // wrap right away
        if (arg == "--verbose") {
            std::println("verbose mode on");
        }
    }
}

Converting each argv[i] into a std::string_view or std::string immediately lets the rest of the program use modern tools. (Our online editor runs programs without arguments, so argc is 1 there.)

Why you should prefer std::string

Concern C string (char[], char*) std::string
Length O(n) strlen, every time O(1) size()
Growing fixed size; you manage buffers grows automatically
Copy, compare, concatenate strcpy, strcmp, strcat =, ==, +
Overflow risk high none for normal use
Embedded '\0' impossible allowed
Memory management manual for dynamic strings automatic (RAII)
Passing to C APIs direct c_str()

Use std::string to own text, std::string_view to look at it, and C strings only at the edges of your program where a C API demands them. Even there, convert as late as possible on the way out and as early as possible on the way in.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. char city[] = "Rome"; What is sizeof city?

    The array holds the 4 letters plus the null terminator, so it is 5 bytes. strlen(city) would be 4.
  2. 2. What does if (std::strcmp(a, b)) { ... } test?

    strcmp returns 0 for equal strings, and 0 converts to false. A non-zero result (different strings) makes the condition true. Write == 0 or != 0 explicitly.
  3. 3. Two char arrays both contain "hi". Through pointers p and q to them, what does p == q compare?

    With C strings, == compares pointers. Two separate arrays have different addresses even if their text is the same. Use strcmp or compare std::string_view values.
  4. 4. What is the danger of std::strncpy(dst, src, sizeof dst) when src is longer than dst?

    strncpy stops after n characters, but it only adds '\0' if it reached the end of src first. You must terminate the buffer yourself, or use snprintf or std::string instead.
  5. 5. Which line is an error in modern C++?

    A string literal is an array of const char. Binding it to a non-const char* would let you modify read-only memory, so modern C++ rejects it.

Summary

  • A C string is a char array ended by '\0'; the literal "code" occupies 5 bytes and has type const char[5].
  • sizeof gives the array's size; std::strlen counts characters to the terminator in O(n).
  • <cstring>: strlen, strcpy, strcat, strcmp (0 means equal), strchr, strstr, memcpy.
  • == on C strings compares addresses. Use strcmp or std::string_view.
  • strcpy and strcat can overflow buffers; strncpy may omit the terminator. snprintf is the safest C tool.
  • Convert with std::string s = cstr;, std::string(ptr, len), s.c_str() and a length-checked s.copy.
  • Own text with std::string, view it with std::string_view, and use C strings only at C API boundaries.

Next: if, else if and else, where your programs start making decisions.