Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 5 – Arrays, vectors and aggregate types

C-style strings and why std::string replaced them

How null-terminated C strings work, why strcpy overflows and == misleads, how to use strlen, strcmp and snprintf safely, and how to convert to std::string.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Explain how null-terminated strings work
  • Use strlen, strcmp and snprintf correctly
  • Detect the buffer overflows that strcpy and strcat allow
  • Convert safely between C strings and std::string

Before you start

A 14-letter name joined to "Hello, " in a 16-byte buffer wrote 6 bytes past its end, and the Clang build died inside std::println with an error that says nothing about the real cause. A null-terminated string: A sequence of characters followed by a zero byte, '\0', which is how C functions such as std::puts and std::fopen find its end. std::string::c_str() always gives one; std::string_view::data() need not. More in “std::string and std::string_view” is an array of char whose end is marked by the null character '\0', a byte with the value 0. Nothing else records its length: std::strlen finds it by walking through the characters until it meets that byte. The functions that copy and join such strings, std::strcpy and std::strcat, never check whether the destination is big enough, and == compares where two strings are in memory, not what they say. Decades of C programs have crashed, or been broken into, through exactly these gaps.

std::string replaced them because it closes every gap: it stores its length, owns and grows its memory, compares text with ==, and joins strings with +. C strings have not gone away, though. Every string literal: Text in double quotes in the source, such as "pune": an array of const char holding the characters and a terminating '\0', made before the program starts and kept for its whole run. Writing into one is undefined behaviour. is one, main receives its arguments as C strings, and C libraries and operating-system calls take them.

A C string is characters followed by ‘\0’

The sections below show how they work, the three classic mistakes with recordings from Apple clang and GCC 16, and how to move safely between the two kinds of string. First, one C string byte by byte: the diagram shows "Pune" in memory, and the program prints each of its bytes.

char city[] = "Pune" is five bytes ending in '\0'; strlen counts the four before it, while a std::string stores its size.char city[] = "Pune": 5 bytesstd::strlen(city) walks from [0] and stopsat the first '\0': 4 charactersstd::string city = "Pune"[0]'P'[1]'u'[2]'n'[3]'e'[4]'\0'size 4(stored)P u n e \0(characters)a std::string never has to search

How a C string marks its end, and how std::string knows its length

Text description of the diagram

The diagram compares two ways of holding the text "Pune".

  1. char city[] = "Pune" is an array of five chars at indexes 0 to 4: 'P', 'u', 'n', 'e' and the null character '\0', whose value is 0. Nothing else records how long the text is.
  2. std::strlen(city) finds the length by walking from index 0 until it meets the first '\0', so it counts 4 characters. It has to do that walk every time it is called, and it never stops if the '\0' is missing.
  3. A std::string holding "Pune" stores its size, 4, beside the characters, so size() needs no search. It still keeps a '\0' after the characters, so that c_str() can hand them to a function that expects a C string.
layout.cpp C++ · layout.cpp
// A C string is an array of char that ends with the null character '\0'.
#include <cstddef>
#include <cstring>
#include <print>

int main() {
    char city[] = "Pune";               // five chars: 'P', 'u', 'n', 'e' and the terminator '\0'
    std::println("sizeof(city) = {}, std::strlen(city) = {}", sizeof(city), std::strlen(city));
    for (std::size_t i = 0; i < sizeof(city); ++i) {
        if (city[i] == '\0') std::println("city[{}] = {:3}  the terminator", i, static_cast<int>(city[i]));
        else std::println("city[{}] = {:3}  '{}'", i, static_cast<int>(city[i]), city[i]);
    }

    city[2] = '\0';                     // a '\0' in the middle ends the string there
    const char* text = city;
    std::println("after city[2] = '\\0': std::strlen = {}, the string is \"{}\"", std::strlen(text), text);

    std::println("std::strlen(\"café\") = {}: it counts bytes, and é takes two in UTF-8", std::strlen("café"));
}
The bytes of a C string Python · layout_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra layout.cpp -o layout
./layout
g++-16 -std=c++23 -Wall -Wextra layout.cpp -o layout-gcc
./layout-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra layout.cpp -o layout
$ ./layout
sizeof(city) = 5, std::strlen(city) = 4
city[0] =  80  'P'
city[1] = 117  'u'
city[2] = 110  'n'
city[3] = 101  'e'
city[4] =   0  the terminator
after city[2] = '\0': std::strlen = 2, the string is "Pu"
std::strlen("café") = 5: it counts bytes, and é takes two in UTF-8
$ g++-16 -std=c++23 -Wall -Wextra layout.cpp -o layout-gcc
$ ./layout-gcc
sizeof(city) = 5, std::strlen(city) = 4
city[0] =  80  'P'
city[1] = 117  'u'
city[2] = 110  'n'
city[3] = 101  'e'
city[4] =   0  the terminator
after city[2] = '\0': std::strlen = 2, the string is "Pu"
std::strlen("café") = 5: it counts bytes, and é takes two in UTF-8

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 layout_session.py

  • char city[] = "Pune"; copies the literal into an array of five char: the four letters and the terminator. So sizeof(city) is 5 while std::strlen(city) is 4.
  • Each char holds a number: 80 is 'P' in ASCII, and the terminator is 0.
  • Writing a '\0' into the middle ends the string there: std::strlen stops at the first one it meets, and so does every function that prints or copies the string.
  • std::strlen counts bytes, not letters: "café" is 5 bytes, because UTF-8 stores é in two.
  • Because the length is never stored, each std::strlen call walks the whole string again. A loop such as for (i = 0; i < strlen(s); ++i) walks it once per step.
Unicode Character Inspector Paste any text to see each character with its UTF-8 bytes: the number std::strlen counts.

std::strlen is a search: it checks one byte after another for the value 0, and where it finds it is the length. Run it on the five bytes of city as layout.cpp printed them, 80, 117, 110, 101 and 0:

Interactive · step through it std::strlen(city): each byte of Pune checked for 0 Check each value from the left until the target turns up or the array ends.
Array of 5: 80 117 110 101 0.80011711102101304
  • being compared or looked at
  • in its final place
  • visited or ruled out

Pseudo-code

  1. for i from 0 to n − 1:
  2. if a[i] = target: return i
  3. return "not found"

Look for 0 by checking each value from the left until it turns up or the array ends.

When it finishes: Found 0 at index 4.

Values checked 0

The search checked 5 values and found 0 at index 4, so the length of "Pune" is 4.

Cut the string in two

Type 80, 117, 0, 101, 0 as the values, the bytes after city[2] = '\0': the search stops at index 2, the length std::strlen reported then.

One difference matters: this search stops at the end of the array, while std::strlen knows no end, and without a '\0' it reads on past the last byte.

Key idea

A C string stores no length: std::strlen finds it by walking to the first '\0', every time it is called.

Checkpoint

Check: How a C string marks its end

  1. Question 1 of 2 char pin[] = "MH12"; What is sizeof(pin)?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 5 bytes

    The array holds the four characters and the terminator, 5 bytes, just as city held Pune in 5. std::strlen(pin) is 4.

  2. Question 2 of 2 char city[] = "Pune"; city[1] = '\0'; What does std::strlen(city) return now?

    Type a number.

    A hint

    Where is the first '\0' after the change?

    Show the answer: Question 2 of 2

    Answer: 1 characters

    strlen stops at the first '\0' it meets, now at index 1, so only P counts. sizeof(city) is still 5: the array did not change size, only the text it holds.

String literals are read-only

A string literal such as "pune" is an array of const char, created before the program starts and kept for its whole run, and the standard leaves the effect of changing one undefined. Since C++11, the standard no longer lets a literal convert to a plain char*, although compilers still accept it, with a warning, for the sake of old code:

literal.cpp C++ · literal.cpp
// A string literal is an array of const char, kept in memory that the program may not change.
#include <cstdio>
#include <print>

int main() {
    char copy[] = "pune";        // an array initialised with a copy of the literal: yours to change
    copy[0] = 'P';
    std::println("{}", copy);
    std::fflush(stdout);         // print the line above now, before the crash below

    char* p = "pune";            // not allowed since C++11: the literal is const
    p[0] = 'P';                  // writing into the literal: undefined behaviour
    std::println("{}", p);
}
Changing a copy, then the literal itself Python · literal_session.py
from session import run

# Both compilers warn about char* p = "pune"; writing through p then crashes, because literals are read-only.
run("""
clang++ -std=c++23 -Wall -Wextra literal.cpp -o literal
./literal
g++-16 -std=c++23 -Wall -Wextra literal.cpp -o literal-gcc
./literal-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra literal.cpp -o literal
literal.cpp:11:15: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings]
   11 |     char* p = "pune";            // not allowed since C++11: the literal is const
      |               ^
1 warning generated.
$ ./literal
Pune
[stopped by SIGBUS: a shell reports exit status 138]
$ g++-16 -std=c++23 -Wall -Wextra literal.cpp -o literal-gcc
literal.cpp: In function 'int main()':
literal.cpp:11:15: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   11 |     char* p = "pune";            // not allowed since C++11: the literal is const
      |               ^~~~~~
$ ./literal-gcc
Pune
[stopped by SIGBUS: a shell reports exit status 138]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 literal_session.py

Both compilers warn about char* p = "pune"; (-Wwritable-strings in Clang, -Wwrite-strings in GCC), and both programs crashed on the write with SIGBUS: the literal sits in memory that the program may only read. The copy in char copy[] = "pune"; is an ordinary array, so changing it is fine. Point to literals with const char*, and copy them into an array or a std::string when you need to change the text. The std::fflush(stdout) is there because output that is still waiting in a buffer is lost when a program crashes.

Step through literal.cpp and watch which "pune" each line touches:

Interactive · step by step Two ways to hold "pune" in literal.cpp Step through the program. The left column is the memory that holds the literal, the right one main's variables; an arrow means a pointer to the literal.
Two ways to hold "pune" in literal.cpp, step 5 of 5. Showing the literal "pune" (read-only: SIGBUS), char copy[] = "pune" (now holds Pune), char* p = "pune". In focus: char* p = "pune", the literal "pune".copied oncepoints into itthe literal "pune"read-only: SIGBUSchar copy[] = "pune"now holds Punechar* p = "pune"a pointer, 8 bytes

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. The literal. A string literal is an array of const char, here p, u, n, e and the terminator: five bytes made before the program starts and kept for its whole run, in memory the program may only read.
  2. A copy of your own. char copy[] = "pune"; makes an ordinary array of five chars in main and copies the literal's bytes into it. The array is main's to change.
  3. Changing the copy. copy[0] = 'P'; changes the array, not the literal, and the program printed Pune.
  4. A pointer to the literal. char* p = "pune"; drops the const, which C++ has not allowed since C++11. Both compilers accept it with a warning, -Wwritable-strings in Clang and -Wwrite-strings in GCC.
  5. Writing into it. p[0] = 'P'; writes into the literal itself, which is undefined behaviour. Its memory is read-only on this Mac, so both builds were stopped by SIGBUS, exit status 138.

The two names look alike in the source, but only copy is memory of main’s own; p points into the literal.

Hex Viewer & File Inspector Open a compiled program and search for a string literal: its bytes end with 00, the terminator.

Checkpoint

Check: Read-only string literals

  1. Question 1 of 2 Which declaration gives you text that you may change?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: char copy[] = "pune";

    Only an array initialised from the literal is memory of your own. Every pointer made from "pune" points at the literal, which the program may only read.

  2. Question 2 of 2 What stopped both builds of literal.cpp at p[0] = 'P';?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The write hit read-only memory, so the system stopped the program with SIGBUS

    Writing into a string literal is undefined behaviour. On this Mac its bytes sit in read-only memory, so the write was stopped by SIGBUS, after Pune had already been printed from the copy.

Compare the characters with std::strcmp, not the addresses

Both files below hold the text pune in two separate arrays. compare.cpp compares them through pointers and with std::strcmp, and compare_arrays.cpp puts == between the two arrays themselves:

compare.cpp, and == between two arrays

C++ (compare.cpp) · compare.cpp

// Two arrays that hold the same text: == on pointers compares addresses, std::strcmp compares the characters.
#include <cstring>
#include <print>

int main() {
    char typed[] = "pune";
    char stored[] = "pune";
    const char* a = typed;
    const char* b = stored;
    std::println("a == b: {}", a == b);                                  // two arrays, two addresses
    std::println("std::strcmp(a, b) == 0: {}", std::strcmp(a, b) == 0);   // the same characters
    std::println("std::strcmp(\"apple\", \"banana\") < 0: {}", std::strcmp("apple", "banana") < 0);
    std::println("std::strcmp(\"Zoo\", \"apple\") < 0: {}", std::strcmp("Zoo", "apple") < 0);   // 'Z' is 90, 'a' is 97
}

C++ (compare_arrays.cpp) · compare_arrays.cpp

// == between two arrays: deprecated since C++20, an error in C++26.
#include <print>

int main() {
    char typed[] = "pune";
    char stored[] = "pune";
    std::println("{}", typed == stored);
}
== and strcmp, then == between two arrays Python · compare_session.py
from session import run

# compare.cpp with both compilers, then == between two arrays in C++23 and in C++26 mode (-std=c++2c).
run("""
clang++ -std=c++23 -Wall -Wextra compare.cpp -o compare
./compare
g++-16 -std=c++23 -Wall -Wextra compare.cpp -o compare-gcc
./compare-gcc
clang++ -std=c++23 -Wall -Wextra compare_arrays.cpp -o compare_arrays 2>&1 | grep -E "warning|error"
g++-16 -std=c++23 -Wall -Wextra compare_arrays.cpp -o compare_arrays-gcc 2>&1 | grep -E "warning|error"
clang++ -std=c++2c -Wall -Wextra compare_arrays.cpp -o compare_arrays 2>&1 | grep -E "warning|error"
g++-16 -std=c++2c -Wall -Wextra compare_arrays.cpp -o compare_arrays-gcc 2>&1 | grep -E "warning|error"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra compare.cpp -o compare
$ ./compare
a == b: false
std::strcmp(a, b) == 0: true
std::strcmp("apple", "banana") < 0: true
std::strcmp("Zoo", "apple") < 0: true
$ g++-16 -std=c++23 -Wall -Wextra compare.cpp -o compare-gcc
$ ./compare-gcc
a == b: false
std::strcmp(a, b) == 0: true
std::strcmp("apple", "banana") < 0: true
std::strcmp("Zoo", "apple") < 0: true
$ clang++ -std=c++23 -Wall -Wextra compare_arrays.cpp -o compare_arrays 2>&1 | grep -E "warning|error"
compare_arrays.cpp:7:30: warning: comparison between two arrays is deprecated; to compare array addresses, use unary '+' to decay operands to pointers [-Wdeprecated-array-compare]
compare_arrays.cpp:7:30: warning: array comparison always evaluates to false [-Wtautological-compare]
2 warnings generated.
$ g++-16 -std=c++23 -Wall -Wextra compare_arrays.cpp -o compare_arrays-gcc 2>&1 | grep -E "warning|error"
compare_arrays.cpp:7:30: warning: comparison between two arrays is deprecated in C++20 [-Warray-compare]
$ clang++ -std=c++2c -Wall -Wextra compare_arrays.cpp -o compare_arrays 2>&1 | grep -E "warning|error"
compare_arrays.cpp:7:30: error: comparison between two arrays is ill-formed in C++26; to compare array addresses, use unary '+' to decay operands to pointers [-Warray-compare-cxx26]
compare_arrays.cpp:7:30: warning: array comparison always evaluates to false [-Wtautological-compare]
1 warning and 1 error generated.
$ g++-16 -std=c++2c -Wall -Wextra compare_arrays.cpp -o compare_arrays-gcc 2>&1 | grep -E "warning|error"
compare_arrays.cpp:7:30: error: comparison between two arrays is not allowed in C++26 [-Warray-compare]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 compare_session.py

  • a == b on two const char* compares two addresses. The two arrays hold the same text in different places, so the answer is false.
  • std::strcmp(a, b) compares the characters one by one and returns 0 when they are all equal, a negative number when a comes first and a positive number when b does. It compares the byte values, so every uppercase ASCII letter comes before every lowercase one: "Zoo" sorts before "apple".
  • Comparing two arrays directly, typed == stored, has been deprecated since C++20, and both compilers warn. C++26 removes it: with -std=c++2c (C++26 mode), Clang and GCC both refuse to compile it.
  • With string literals the result of == is not even predictable: the standard leaves it unspecified whether two identical literals are the same object, so "pune" == "pune" may be true or false.

Step through two of the program’s calls and watch std::strcmp compare one pair of bytes at a time:

Interactive · stage by stage std::strcmp, one pair of bytes at a time Step through std::strcmp on two arrays that hold pune, then on Zoo and apple. The sub-labels show the pair of bytes being compared.
std::strcmp, one pair of bytes at a time, step 5 of 5. Showing a[i] equals b[i] ? (Z is 90, a is 97), a[i] is the terminator ? (both strings ended), ++i, the first difference (negative: Zoo first). In focus: the first difference.compare againa[i] equals b[i] ?Z is 90, a is 97a[i] is the terminator ?both strings ended++ithe next pairthe first differencenegative: Zoo first

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. p and p. std::strcmp(a, b) with both arrays holding pune starts at i = 0: p against p. The bytes are equal and neither is the terminator, so it moves on.
  2. u, n and e. The next three pairs, u, n and e, are equal too. strcmp never looks at where the two arrays are, only at their bytes.
  3. Both ended. At i = 4 both bytes are the terminator, so the strings ended together with no difference: strcmp returns 0, and the program printed std::strcmp(a, b) == 0: true.
  4. Z and a. std::strcmp("Zoo", "apple") differs at the very first pair: Z is the byte 90 and a is 97.
  5. The first difference decides. 90 is below 97, so strcmp returns a negative number and Zoo sorts before apple, as the program printed: std::strcmp("Zoo", "apple") < 0: true. Every uppercase ASCII letter comes before every lowercase one.

The two arrays holding pune took five comparisons to come out equal, and "Zoo" against "apple" was decided by the first pair alone.

Checkpoint

Check: Comparing with std::strcmp

  1. Question 1 of 2 Two arrays both hold "pune", and a and b point to them. What does a == b compare?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Their addresses, which differ, so it is false

    Two arrays holding the same text are two places in memory, so their addresses differ. std::strcmp(a, b) == 0 compares the text, and it printed true.

  2. Question 2 of 2 Is std::strcmp("Delhi", "agra") negative, zero or positive?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Negative, because D is the byte 68 and a is 97

    strcmp walks both strings until a pair of bytes differs. D (68) is below a (97), so the result is negative, just as Zoo came before apple.

strcpy and strcat never check the size of the destination

std::strcpy(dest, src) copies characters until it has copied the '\0', and std::strcat(dest, src) appends the same way. Neither knows how big dest is:

overflow.cpp C++ · overflow.cpp
// std::strcat appends until it has copied the '\0', however small the destination is.
#include <cstring>
#include <print>

void greet(const char* name) {
    char buffer[16];
    std::strcpy(buffer, "Hello, ");     // 7 characters and '\0': fits
    std::strcat(buffer, name);          // appends name: nothing checks that it fits
    std::println("{}", buffer);
}

int main(int argc, char* argv[]) {
    greet(argc > 1 ? argv[1] : "Asha");
}
A name that fits, and one that does not Python · overflow_session.py
from session import run

# A short name fits; a 14-letter name overflows the 16-byte buffer. Without a checker the result depends on the
# compiler: Clang's build dies inside println, GCC's -O2 build seems to work. AddressSanitizer names the bug (grep
# keeps the key lines of its report, sed hides the addresses).
run("""
clang++ -std=c++23 -Wall -Wextra overflow.cpp -o overflow
./overflow Ravi
./overflow Venkataramanan
g++-16 -std=c++23 -O2 -Wall -Wextra overflow.cpp -o overflow-gcc
./overflow-gcc Venkataramanan
clang++ -std=c++23 -g -fsanitize=address overflow.cpp -o overflow-asan
ASAN_OPTIONS=symbolize=0 ./overflow-asan Venkataramanan 2>&1 | grep -E "ERROR|of size|overflows" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
""")

Output

$ clang++ -std=c++23 -Wall -Wextra overflow.cpp -o overflow
$ ./overflow Ravi
Hello, Ravi
$ ./overflow Venkataramanan
libc++abi: terminating due to uncaught exception of type std::bad_alloc: std::bad_alloc
[stopped by SIGABRT: a shell reports exit status 134]
$ g++-16 -std=c++23 -O2 -Wall -Wextra overflow.cpp -o overflow-gcc
$ ./overflow-gcc Venkataramanan
Hello, Venkataramanan
$ clang++ -std=c++23 -g -fsanitize=address overflow.cpp -o overflow-asan
$ ASAN_OPTIONS=symbolize=0 ./overflow-asan Venkataramanan 2>&1 | grep -E "ERROR|of size|overflows" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
ERROR: AddressSanitizer: stack-buffer-overflow on address 0x… at pc 0x… bp 0x… sp 0x…
WRITE of size 15 at 0x… thread T0
    [32, 48) 'buffer' (line 6) <== Memory access at offset 48 overflows this variable

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 overflow_session.py

"Hello, Ravi" fits into 16 bytes. "Hello, Venkataramanan" needs 22, so strcat wrote 6 bytes past the end of buffer, over whatever the compiler had placed there. The Clang build then died with a std::bad_alloc exception thrown inside std::println, a message that says nothing about the real cause. The GCC -O2 build printed the whole greeting and seemed fine: the overflow was still there, it just damaged nothing that this short program used afterwards. sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan” names the bug, a buffer overflow: Writing or reading past the end of a block of memory, as std::strcat does when its destination is too small. The extra bytes land on whatever lies next to the buffer: undefined behaviour, and a classic security hole. AddressSanitizer names it, for example a stack-buffer-overflow.: a write of 15 bytes, the name and its terminator, that runs past the 16 bytes of buffer. Overflows like this one are also a classic security hole: input chosen by an attacker can overwrite data the program relies on, such as the place a function returns to.

Step through greet with both names and watch the bytes go into buffer:

Interactive · step by step Sixteen bytes, two names and std::strcat Step through greet with Ravi, then with Venkataramanan. The left column is buffer, the right one the text that goes into it.
Sixteen bytes, two names and std::strcat, step 6 of 6. Showing char buffer[16] (full after 16 bytes), the bytes after buffer (overwritten: 6 bytes), strcpy: "Hello, ", strcat: Venkataramanan. In focus: char buffer[16], the bytes after buffer.8 bytesneeds 22 of 166 bytes run onchar buffer[16]full after 16 bytesthe bytes after bufferoverwritten: 6 bytesstrcpy: "Hello, "7 characters and \0strcat: Venkataramanan14 characters and \0stack-buffer-overflow

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Room for 16. greet has a local char buffer[16]: room for 15 characters and the terminator. Nothing records that size where strcpy or strcat could see it.
  2. The greeting. std::strcpy(buffer, "Hello, ") copies 7 characters and the terminator, 8 bytes, which fit.
  3. A short name. std::strcat(buffer, name) appends from the old terminator on. Ravi adds 4 characters and a new terminator: 12 bytes in all, and the program printed Hello, Ravi.
  4. A long name. In the next run the name is Venkataramanan, 14 characters. Hello, and the name need 7 + 14 + 1 = 22 bytes, and strcat copies all of them, because nothing tells it the buffer ends at 16.
  5. Past the end. The last 6 bytes land after buffer, on whatever the compiler placed there. The Clang build then died with std::bad_alloc inside std::println, and the GCC -O2 build printed the whole greeting.
  6. The checker names it. AddressSanitizer stopped the write itself: a stack-buffer-overflow, a WRITE of size 15, the 14 letters and the terminator, that overflows buffer, which takes offsets 32 to 47 of the frame.

Neither call was given the 16: strcpy and strcat only know where the text starts, so the size of the destination is the caller’s to check.

Input of unknown length in a fixed buffer

Never copy or append text you did not write into a fixed buffer with std::strcpy or std::strcat. Use std::snprintf, which takes the size, or a std::string, which grows to fit, and test with AddressSanitizer and a name longer than the buffer.

Checkpoint

Check: Overflows from strcpy and strcat

  1. Question 1 of 2 "Hello, " (7 characters) and a 14-letter name are joined, with their terminator, in a 16-byte buffer. How many bytes land past its end?

    Type a number.

    A hint

    Add the characters and the terminator, then compare with 16.

    Show the answer: Question 1 of 2

    Answer: 6 bytes

    7 + 14 + 1 = 22 bytes are written into 16, so 6 land after buffer, as the run with Venkataramanan showed.

  2. Question 2 of 2 AddressSanitizer reported a WRITE of size 15 for Venkataramanan. What were those 15 bytes?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The 14 letters of the name and the terminator, written by std::strcat

    strcat copies the 14 letters and the terminator, 15 bytes, starting after the 7 characters of Hello, so the copy runs on past byte 16 of buffer. AddressSanitizer stopped the program at that write.

snprintf takes the size, ends the text and reports what it needed

When you must fill a fixed buffer, use a function that takes its size. std::snprintf writes at most the size you give it, always ends the text with '\0', and returns the length the whole text would have had:

bounded.cpp C++ · bounded.cpp
// std::snprintf writes at most the size it is given, always ends with '\0',
// and returns the length the whole text would have had.
#include <cstddef>
#include <cstdio>
#include <print>

int main() {
    char line[12];
    int needed = std::snprintf(line, sizeof line, "%s scored %d", "Asha", 74);
    std::println("needed {}, room for {} plus '\\0': \"{}\"", needed, sizeof line - 1, line);
    if (needed >= static_cast<int>(sizeof line)) std::println("the text was cut short");

    char wide[32];
    needed = std::snprintf(wide, sizeof wide, "%s scored %d", "Asha", 74);
    std::println("with 32 bytes: needed {}, \"{}\"", needed, wide);
}
snprintf cuts the text instead of overflowing Python · bounded_session.py
from session import run

# GCC sees the truncation while compiling (-Wformat-truncation, part of -Wall); both programs print the same.
run("""
clang++ -std=c++23 -Wall -Wextra bounded.cpp -o bounded
./bounded
g++-16 -std=c++23 -Wall -Wextra bounded.cpp -o bounded-gcc
./bounded-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra bounded.cpp -o bounded
$ ./bounded
needed 14, room for 11 plus '\0': "Asha scored"
the text was cut short
with 32 bytes: needed 14, "Asha scored 74"
$ g++-16 -std=c++23 -Wall -Wextra bounded.cpp -o bounded-gcc
bounded.cpp: In function 'int main()':
bounded.cpp:9:31: warning: '%d' directive output truncated writing 2 bytes into a region of size 0 [-Wformat-truncation=]
    9 |     int needed = std::snprintf(line, sizeof line, "%s scored %d", "Asha", 74);
      |                  ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bounded.cpp:9:31: note: 'snprintf' output 15 bytes into a destination of size 12
$ ./bounded-gcc
needed 14, room for 11 plus '\0': "Asha scored"
the text was cut short
with 32 bytes: needed 14, "Asha scored 74"

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 bounded_session.py

The text needed 14 characters and the buffer had room for 11, so snprintf stored "Asha scored" and returned 14: a return value that is not smaller than the buffer’s size means the text was cut short. GCC even noticed the cut while compiling, with its -Wformat-truncation warning. Avoid std::strncpy for this job: when the source is too long it fills the destination without a terminator, so the next strlen runs off its end.

Step through the first call of bounded.cpp, from the whole text to the test that caught the cut:

Interactive · stage by stage std::snprintf into a 12-byte buffer Step through the call std::snprintf(line, sizeof line, "%s scored %d", "Asha", 74). The sub-labels show what each stage holds.
std::snprintf into a 12-byte buffer, step 4 of 4. Showing the whole text, at most 11 and \0 (line holds "Asha scored"), returns 14, needed >= sizeof line ? (14 >= 12: cut short). In focus: needed >= sizeof line ?.the whole textAsha scored 74: 14 charactersat most 11 and \0line holds "Asha scored"returns 14the length it neededneeded >= sizeof line ?14 >= 12: cut short

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. What the text would be. snprintf works out the whole text first: Asha, scored and 74 make Asha scored 74, 14 characters.
  2. What fits. line has 12 bytes, so snprintf writes at most 11 characters and always ends them with the terminator: line holds Asha scored, as the program printed.
  3. What it needed. The return value is not what it wrote but what the whole text needed, 14 characters, so the caller can tell that something was left out.
  4. Telling that it was cut. 14 is not smaller than 12, the size of the buffer, so the program printed the text was cut short. With 32 bytes the same call stored Asha scored 74 and also returned 14.

The cut was not silent: the return value, 14 against a size of 12, told the program, and it printed the text was cut short. The two kinds of string side by side:

C string or std::string?
Criterion C string (char array)std::string
Length Found by walking to '\0', every timeStored: size() takes one step
Memory A fixed buffer that you size yourselfGrows by itself and frees itself
Copy and join strcpy and strcat, unchecked= and +, which never overflow
Compare text strcmp(a, b) == 0a == b
A '\0' inside the text Ends the stringAn ordinary character
When to choose Talking to C functions, and string literalsEvery string your own code builds, keeps or changes

Checkpoint

Check: Bounded writes with snprintf

  1. Question 1 of 2 char buf[16]; int n = std::snprintf(buf, sizeof buf, "%s scored %d", "Asha", 74); n is 14. Was the text cut?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: No, because 14 is smaller than 16, so all 14 characters and the terminator fit

    snprintf returns the length the whole text needed. When that is smaller than the buffer's size, the text and its terminator fitted; when it is the size or more, the text was cut.

  2. Question 2 of 2 Why does the lesson tell you to avoid std::strncpy for filling a fixed buffer?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: When the source is too long, it fills the destination without a terminator

    std::snprintf always ends the text with '\0' and reports the length it needed; std::strncpy does neither when the source is too long, so a later strlen or print reads past the buffer.

Converting to std::string copies the characters

Going from a C string to a std::string is easy and safe, because the string copies the characters. Going back needs care:

convert.cpp, and a std::string made from nullptr

C++ (convert.cpp) · convert.cpp

// From C strings to std::string and back.
#include <cstddef>
#include <cstring>
#include <print>
#include <string>
#include <string_view>

std::size_t c_api_length(const char* s) { return std::strlen(s); }   // stands for any function that takes a C string

int main() {
    const char* from_c = "Chennai";
    std::string s = from_c;                      // copies the characters up to the '\0'
    s += " Central";                             // s owns its memory and grows as needed
    std::println("{} ({} characters)", s, s.size());
    std::println("a C function sees {} characters", c_api_length(s.c_str()));   // c_str(): a '\0'-terminated copy-free view

    std::string_view view = from_c;              // no copy: a pointer and a length, found with strlen once
    std::println("view {} has {} characters", view, view.size());

    std::string with_zero("ab\0cd", 5);          // a std::string can hold '\0' as an ordinary character
    std::println("size {}, but std::strlen(c_str()) is {}", with_zero.size(), std::strlen(with_zero.c_str()));
}

C++ (from_null.cpp) · from_null.cpp

// A std::string made from a null pointer: undefined behaviour before C++23, a compile error since.
#include <string>

int main() {
    std::string s = nullptr;
    return static_cast<int>(s.size());
}
Both directions, and std::string from nullptr Python · convert_session.py
from session import run

# convert.cpp with both compilers, then a std::string made from nullptr, which C++23 refuses (grep keeps the error lines).
run("""
clang++ -std=c++23 -Wall -Wextra convert.cpp -o convert
./convert
g++-16 -std=c++23 -Wall -Wextra convert.cpp -o convert-gcc
./convert-gcc
clang++ -std=c++23 from_null.cpp -o from_null 2>&1 | grep "error:"
g++-16 -std=c++23 from_null.cpp -o from_null-gcc 2>&1 | grep "error:"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra convert.cpp -o convert
$ ./convert
Chennai Central (15 characters)
a C function sees 15 characters
view Chennai has 7 characters
size 5, but std::strlen(c_str()) is 2
$ g++-16 -std=c++23 -Wall -Wextra convert.cpp -o convert-gcc
$ ./convert-gcc
Chennai Central (15 characters)
a C function sees 15 characters
view Chennai has 7 characters
size 5, but std::strlen(c_str()) is 2
$ clang++ -std=c++23 from_null.cpp -o from_null 2>&1 | grep "error:"
from_null.cpp:5:17: error: conversion function from 'std::nullptr_t' to 'std::string' (aka 'basic_string<char>') invokes a deleted function
$ g++-16 -std=c++23 from_null.cpp -o from_null-gcc 2>&1 | grep "error:"
from_null.cpp:5:21: error: use of deleted function 'std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::nullptr_t) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>; std::nullptr_t = std::nullptr_t]'

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 convert_session.py

  • std::string s = from_c; copies the characters up to the '\0'; after that, s owns its own memory.
  • s.c_str() returns a pointer to the string’s characters followed by a '\0', ready for a function that expects a C string. It is not a copy, so it stays valid only while s exists and is not changed.
  • A std::string_view built from a C string runs strlen once and then remembers the length. Like a C string pointer, it does not own the characters.
  • A std::string may contain '\0' as an ordinary character: with_zero has 5 characters, but a C function given its c_str() sees only the 2 before the first terminator.
  • Making a std::string from a null pointer used to compile, with undefined behaviour, usually a crash, at run time. Since C++23 the standard deletes that constructor, so std::string s = nullptr; is a compile error in both compilers.

Each conversion of convert.cpp and what the program printed for it:

Conversion What it does What it printed
std::string s = from_c copies Chennai, then grows by " Central" Chennai Central (15 characters)
s.c_str() lends s’s own characters and a '\0' a C function sees 15 characters
std::string_view view = from_c counts once with strlen, copies nothing view Chennai has 7 characters
with_zero("ab\0cd", 5) keeps '\0' as a character size 5, but strlen of its c_str() is 2

Only the first row copies characters: the pointer and the view read characters that someone else owns.

Checkpoint

Check: Converting to std::string and back

  1. Question 1 of 2 const char* from_c = "Chennai"; std::string s = from_c; s += " Central"; What happens to the text that from_c points to?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Nothing, because s made its own copy, which grew to Chennai Central

    Making a std::string from a C string copies the characters; after that the string owns its memory, grows it and frees it. convert.cpp printed Chennai Central (15 characters).

  2. Question 2 of 2 std::string t("ab\0cd", 5); What does std::strlen(t.c_str()) return?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 2 characters

    t holds 5 characters, with the '\0' among them. strlen stops at that first '\0', after a and b. convert.cpp printed size 5, but std::strlen(c_str()) is 2.

A pointer into a std::string dies with the string

The pointer from c_str() is the one to watch. Here it outlives the string it points into:

lifetime.cpp C++ · lifetime.cpp
// c_str() points into the string's own memory: valid only while the string lives and is not changed.
#include <cstring>
#include <print>
#include <string>

std::string full_name(const char* first, const char* last) {
    return std::string(first) + " " + last;
}

int main() {
    std::string city = "Bengaluru";
    const char* p = city.c_str();       // fine: city is alive and unchanged
    std::println("{} has {} characters", p, std::strlen(p));

    const char* name = full_name("Venkata", "Ramanan Subramaniam").c_str();
    // The string returned by full_name was a temporary: it was destroyed at the end of the line above.
    std::println("{}", name);
}
A pointer into a destroyed string Python · lifetime_session.py
from session import run

# Clang warns while compiling; AddressSanitizer catches the read of the freed memory (key lines, addresses hidden);
# GCC builds the same file with -Wall -Wextra and prints nothing at all.
run("""
clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address lifetime.cpp -o lifetime
ASAN_OPTIONS=symbolize=0 ./lifetime 2>&1 | grep -E "ERROR|of size|located|freed by|allocated by" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
g++-16 -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime-gcc
""")

Output

$ clang++ -std=c++23 -g -Wall -Wextra -fsanitize=address lifetime.cpp -o lifetime
lifetime.cpp:15:24: warning: object backing the pointer will be destroyed at the end of the full-expression [-Wdangling-gsl]
   15 |     const char* name = full_name("Venkata", "Ramanan Subramaniam").c_str();
      |                        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
$ ASAN_OPTIONS=symbolize=0 ./lifetime 2>&1 | grep -E "ERROR|of size|located|freed by|allocated by" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
ERROR: AddressSanitizer: heap-use-after-free on address 0x… at pc 0x… bp 0x… sp 0x…
READ of size 2 at 0x… thread T0
0x… is located 0 bytes inside of 48-byte region [0x…,0x…)
freed by thread T0 here:
previously allocated by thread T0 here:
$ g++-16 -std=c++23 -Wall -Wextra lifetime.cpp -o lifetime-gcc

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 lifetime_session.py

full_name returns a temporary object: An unnamed object made while an expression is evaluated, such as the std::string that city + ' Central' produces. It is destroyed at the end of the full expression that made it, unless a reference bound to it keeps it alive. More in “std::string and std::string_view” std::string, which is destroyed at the end of the line that called it, together with its buffer. Clang warns while compiling (-Wdangling-gsl), and AddressSanitizer reports the later read as a heap-use-after-free in a 48-byte region, the freed buffer of the 27-character name. GCC compiles the same file without a warning (the last command above prints nothing), so do not rely on one. Keep the std::string in a variable for as long as you use its c_str(), and call c_str() again after any change to the string.

Step through main and follow both pointers that c_str() handed out:

Interactive · step by step Two pointers from c_str() in lifetime.cpp Step through main. The left column holds the strings, the right one the pointers c_str() gave; an arrow shows what each pointer points into.
Two pointers from c_str() in lifetime.cpp, step 5 of 5. Showing std::string city, const char* p, the temporary string (destroyed, buffer freed), const char* name (reads freed memory). In focus: const char* name, the temporary string.points intopoints intostd::string cityBengaluru, alive in mainconst char* pcity.c_str()the temporary stringdestroyed, buffer freedconst char* namereads freed memory

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. A pointer that is fine. p = city.c_str() points at the characters city owns, followed by a terminator. city is alive and unchanged, so the program printed Bengaluru has 9 characters.
  2. A temporary string. full_name("Venkata", "Ramanan Subramaniam") returns a new std::string of 27 characters, too long to fit inside the object, so its characters are in a buffer on the heap.
  3. A pointer into it. name = full_name(…).c_str() keeps a pointer into that buffer. Clang warned on this line: the object backing the pointer will be destroyed at the end of the full-expression.
  4. The end of the line. The temporary string is destroyed at the end of the full expression that made it, line 15, and its destructor frees the buffer. name still points into it.
  5. The read. Line 17 prints name and reads the freed buffer. AddressSanitizer stopped it: a heap-use-after-free, 0 bytes inside a 48-byte region, the buffer of the 27-character name.

p stayed valid because city lived on; name dangled from the end of line 15, before line 17 read it.

Key idea

c_str() lends the string’s own characters: keep the std::string alive, and unchanged, for as long as the pointer is used.

Checkpoint

Check: How long c_str() stays valid

  1. Question 1 of 2 In lifetime.cpp, from which point on does name point at freed memory?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: From the end of line 15, when the temporary string from full_name is destroyed

    full_name returns a temporary std::string, destroyed at the end of line 15, so name dangles before line 17 reads it. AddressSanitizer reported a heap-use-after-free in the 48-byte buffer of the 27-character name.

  2. Question 2 of 2 Which compiler warned about line 15 of lifetime.cpp?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Clang, with -Wdangling-gsl

    Clang's -Wdangling-gsl, on by default, caught this case while compiling; GCC did not. AddressSanitizer catches the read itself in either build.

Practise: write strlen, strcmp and a bounded copy

Writing these three functions yourself is the quickest way to see the rules of this lesson from the inside: the walk to '\0', the comparison of byte values and the terminator that must always be there.

cstring_exercise.cpp C++ · cstring_exercise.cpp
// Exercise: three C-string functions. Write the bodies marked "your code here", then build and run this file:
//   clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined cstring_exercise.cpp -o cstring_exercise
//   ./cstring_exercise
// Every check must say "ok", and the sanitizers must report nothing. Do not call the <cstring> functions in your
// answers: the checks compare your functions with them.
#include <cstddef>
#include <cstring>
#include <print>

// The number of characters before the terminating '\0', like std::strlen.
std::size_t my_strlen(const char* s) {
    return 0;   // your code here
}

// Compares two C strings like std::strcmp: negative if a comes first, 0 if they are equal, positive if b comes first.
// Compare the characters as unsigned char values, as std::strcmp does.
int my_strcmp(const char* a, const char* b) {
    return 0;   // your code here
}

// Copies src into dest, which has room for size chars, and always ends dest with '\0': it copies at most size - 1
// characters, and with size 0 it writes nothing. Returns my_strlen(src), so a result >= size means the copy was cut.
std::size_t bounded_copy(char* dest, std::size_t size, const char* src) {
    return 0;   // your code here
}

int failures = 0;

void check(bool passed, const char* what) {
    std::println("{}  {}", passed ? "ok    " : "FAILED", what);
    if (!passed) ++failures;
}

int sign(int x) { return (x > 0) - (x < 0); }

int main() {
    const char* words[]{"", "a", "Pune", "Thiruvananthapuram"};
    bool lengths_ok = true;
    for (const char* w : words) lengths_ok = lengths_ok && my_strlen(w) == std::strlen(w);
    check(lengths_ok, "my_strlen agrees with std::strlen on \"\", \"a\", \"Pune\" and a long name");

    const char* pairs[][2]{{"apple", "banana"}, {"pune", "pune"}, {"abc", "ab"}, {"Zoo", "apple"}, {"", "x"}};
    bool order_ok = true;
    for (auto& p : pairs) order_ok = order_ok && sign(my_strcmp(p[0], p[1])) == sign(std::strcmp(p[0], p[1]));
    check(order_ok, "my_strcmp has the same sign as std::strcmp on five pairs");
    check(my_strcmp("caf\xc3\xa9", "cafe") > 0, "bytes above 127 compare as unsigned: \"café\" after \"cafe\"");

    char dest[8];
    std::size_t n = bounded_copy(dest, sizeof dest, "Bengaluru");
    check(n == 9 && std::strcmp(dest, "Bengalu") == 0, "\"Bengaluru\" into 8 bytes: \"Bengalu\", returns 9");
    n = bounded_copy(dest, sizeof dest, "Pune");
    check(n == 4 && std::strcmp(dest, "Pune") == 0, "\"Pune\" fits: copied whole, returns 4");
    char one[1]{'x'};
    n = bounded_copy(one, sizeof one, "Agra");
    check(n == 4 && one[0] == '\0', "size 1: only the terminator is written");
    char untouched[4]{'q', 'q', 'q', 'q'};
    n = bounded_copy(untouched, 0, "Agra");
    check(n == 4 && untouched[0] == 'q', "size 0: nothing is written");

    std::println("{} of 7 checks failed", failures);
    return failures == 0 ? 0 : 1;
}

As it starts, every function returns 0, so every check fails:

The starting point Python · exercise_session.py
from session import run

# The exercise as it starts: the functions return 0, so most checks fail.
run("""
clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined cstring_exercise.cpp -o cstring_exercise
./cstring_exercise
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined cstring_exercise.cpp -o cstring_exercise
cstring_exercise.cpp:11:35: warning: unused parameter 's' [-Wunused-parameter]
   11 | std::size_t my_strlen(const char* s) {
      |                                   ^
cstring_exercise.cpp:17:27: warning: unused parameter 'a' [-Wunused-parameter]
   17 | int my_strcmp(const char* a, const char* b) {
      |                           ^
cstring_exercise.cpp:17:42: warning: unused parameter 'b' [-Wunused-parameter]
   17 | int my_strcmp(const char* a, const char* b) {
      |                                          ^
cstring_exercise.cpp:23:32: warning: unused parameter 'dest' [-Wunused-parameter]
   23 | std::size_t bounded_copy(char* dest, std::size_t size, const char* src) {
      |                                ^
cstring_exercise.cpp:23:50: warning: unused parameter 'size' [-Wunused-parameter]
   23 | std::size_t bounded_copy(char* dest, std::size_t size, const char* src) {
      |                                                  ^
cstring_exercise.cpp:23:68: warning: unused parameter 'src' [-Wunused-parameter]
   23 | std::size_t bounded_copy(char* dest, std::size_t size, const char* src) {
      |                                                                    ^
6 warnings generated.
$ ./cstring_exercise
FAILED  my_strlen agrees with std::strlen on "", "a", "Pune" and a long name
FAILED  my_strcmp has the same sign as std::strcmp on five pairs
FAILED  bytes above 127 compare as unsigned: "café" after "cafe"
FAILED  "Bengaluru" into 8 bytes: "Bengalu", returns 9
FAILED  "Pune" fits: copied whole, returns 4
FAILED  size 1: only the terminator is written
FAILED  size 0: nothing is written
7 of 7 checks failed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 exercise_session.py

You are done when it prints 0 of 7 checks failed and the sanitizers report nothing. Hints: in my_strcmp, stop at the first position where the characters differ or where a ends, then subtract the two characters converted to unsigned char; in bounded_copy, handle size == 0 first, and write the terminator after the last character you copy.

Once all seven checks print ok, practise the terminator, literals, comparison, overflows, snprintf, conversions and c_str() below. The session opens where your earlier answers were weakest and explains every pick at once:

Practice that adapts to you

Practise this lesson

20 questions about 7 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 20 char code[] = "IN-560001"; What is sizeof(code)?

    Type a number.

    Show the answer: Question 1 of 20

    Answer: 10 bytes

    The literal has 9 characters, and the array also holds the terminating '\0', so it is 10 bytes. std::strlen(code) is 9: it counts the characters before the terminator.

  2. Question 2 of 20 What is the null character '\0' that ends a C string?

    Choose one answer.

    Show the answer: Question 2 of 20

    Answer: A char whose value is 0

    '\0' is the char with the value 0. Every function that reads a C string stops at the first one, and nothing else in memory marks where the text ends.

  3. Question 3 of 20 for (std::size_t i = 0; i < std::strlen(s); ++i) runs over a string of 1,000 characters. About how many characters do the loop tests alone read?

    Choose one answer.

    Show the answer: Question 3 of 20

    Answer: About a million, because each of the 1,001 tests walks all 1,000 characters

    Each test calls std::strlen, which walks to the '\0': 1,001 tests of 1,000 characters each come to about a million reads. Store the length once, or use std::string, whose size() takes one step.

  4. Question 4 of 20 What does C++ say about char* p = const_cast<char*>("pune"); p[0] = 'P';?

    Choose one answer.

    Show the answer: Question 4 of 20

    Answer: Writing into a string literal is undefined behaviour

    A string literal is an array of const char that the program may not change; on this Mac the write crashed with SIGBUS because the literal sits in read-only memory. const_cast only silences the compiler. Copy the literal into an array, char copy[] = "pune";, or use std::string when you need to change the text.

  5. Question 5 of 20 void shout(char* s) turns its text into capitals in place. Which call is safe?

    Choose one answer.

    Show the answer: Question 5 of 20

    Answer: char word[] = "pune"; shout(word);

    A function that changes its text needs memory the caller owns: an array initialised from the literal, or the characters of a std::string through data(). Every pointer to the literal itself is read-only, whatever cast hides it.

  6. Question 6 of 20 const char* a = typed; and const char* b = stored; point to two arrays that both hold "pune". Which test is true exactly when they hold the same text?

    Choose one answer.

    Show the answer: Question 6 of 20

    Answer: std::strcmp(a, b) == 0

    a == b compares two addresses, which differ for two arrays. *a == *b compares only the first characters, and equal lengths say nothing about the characters. std::strcmp compares character by character and returns 0 when the texts are the same.

  7. Question 7 of 20 What does std::strcmp(a, b) return when a and b hold the same text?

    Choose one answer.

    Show the answer: Question 7 of 20

    Answer: 0

    strcmp returns 0 for equal texts, a negative number when a comes first and a positive one when b does, so the test for equal text is std::strcmp(a, b) == 0.

  8. Question 8 of 20 Sorting "apple", "Zoo" and "banana" with std::strcmp gives which order?

    Choose one answer.

    Show the answer: Question 8 of 20

    Answer: Zoo, apple, banana

    strcmp orders by byte values. Z (90) is below every lowercase letter, so Zoo comes first, and then apple before banana because a (97) is below b (98).

  9. Question 9 of 20 How does std::strcat(dest, src) know how big dest is?

    Choose one answer.

    Show the answer: Question 9 of 20

    Answer: It does not; it appends until it has copied the terminator of src

    std::strcpy and std::strcat know where the text starts and stop at its terminator. Nothing tells them where the destination ends, so a text that is too long runs past it.

  10. Question 10 of 20 The GCC -O2 build printed Hello, Venkataramanan and ended normally. Was the overflow there?

    Choose one answer.

    Show the answer: Question 10 of 20

    Answer: Yes; strcat still wrote 6 bytes past buffer, and they damaged nothing this program used afterwards

    An overflow that prints the right text is still an overflow. AddressSanitizer reported the same write that the GCC build survived, which is why tests should run under it with input longer than the buffer.

  11. Question 11 of 20 What is the smallest char buffer that holds "Hello, " followed by the 14-letter name Venkataramanan, terminator included?

    Type a number.

    Show the answer: Question 11 of 20

    Answer: 22 bytes

    7 + 14 characters and 1 terminator make 22 bytes. A buffer of 21 would still overflow by one byte, the terminator.

  12. Question 12 of 20 char buf[6]; int n = std::snprintf(buf, sizeof buf, "%d runs", 120); The full text would be 120 runs. What is n?

    Type a number.

    Show the answer: Question 12 of 20

    Answer: 8 characters

    snprintf returns the length the whole text would have had, 8 characters, whatever the size of the buffer. It wrote only 120 r and the terminator. A return value that is not smaller than the buffer size means the text was cut short.

  13. Question 13 of 20 When std::snprintf cuts a text short, what does it write right after the last character it keeps?

    Choose one answer.

    Show the answer: Question 13 of 20

    Answer: The terminator, '\0'

    snprintf writes at most size - 1 characters and then '\0'. That is why bounded.cpp could print "Asha scored" safely, and why the return value, not the text, tells you about the cut.

  14. Question 14 of 20 Which test after int n = std::snprintf(buf, sizeof buf, …); tells you that the text was cut?

    Choose one answer.

    Show the answer: Question 14 of 20

    Answer: n >= static_cast<int>(sizeof buf)

    A text of n characters needs n + 1 bytes. When n is the buffer's size or more, those n + 1 bytes did not fit, so the text was cut; bounded.cpp printed the text was cut short for n = 14 and a size of 12.

  15. Question 15 of 20 std::string_view view = from_c; What does view own?

    Choose one answer.

    Show the answer: Question 15 of 20

    Answer: Nothing, because it is a pointer and a length into characters someone else owns

    A std::string_view made from a C string counts the characters with strlen once and keeps a pointer and that length. It owns nothing, which is what makes it cheap.

  16. Question 16 of 20 std::string_view view = "Chennai Central"; What is view.size()?

    Type a number.

    Show the answer: Question 16 of 20

    Answer: 15 characters

    Building the view runs strlen once: 15 characters, the length s had in convert.cpp. After that the view remembers the number and never walks the text again.

  17. Question 17 of 20 A function receives const char* name, which may be a null pointer, and stores it in a std::string. What must it do?

    Choose one answer.

    Show the answer: Question 17 of 20

    Answer: Check name for nullptr first, because making a std::string from a null pointer is still undefined behaviour

    The deleted constructor catches std::string s = nullptr; while compiling. A const char* that is null at run time goes to the ordinary constructor, which reads the characters, so the function must test name first.

  18. Question 18 of 20 When does the pointer returned by s.c_str() stop being safe to use?

    Choose one answer.

    Show the answer: Question 18 of 20

    Answer: When s is destroyed or changed by a call that can change its characters or its size

    c_str() returns a pointer into the string's own buffer, not a copy. Destroying the string frees that buffer, and changing the string can move its characters to a new buffer. The lesson's example used a pointer into a temporary string after the end of its line, and AddressSanitizer reported a heap-use-after-free.

  19. Question 19 of 20 How do you fix line 15 of lifetime.cpp?

    Choose one answer.

    Show the answer: Question 19 of 20

    Answer: Keep the string, std::string name = full_name(…);, and call name.c_str() where a C string is needed

    The pointer was fine; what it pointed into was not kept. Keeping the std::string in a variable keeps its buffer alive for every later use of c_str().

  20. Question 20 of 20 std::string s = "Pune"; const char* p = s.c_str(); s += " Junction, a long name"; Can p still be used?

    Choose one answer.

    Show the answer: Question 20 of 20

    Answer: No, because the append may have moved the characters into a bigger buffer, so call c_str() again

    c_str() is valid only while the string is alive and unchanged. Appending 22 characters to Pune makes the string need more room, and a std::string that grows may move its characters to a new buffer.

Interview questions

Fresher · Why does strlen(“hello”) return 5 while sizeof(“hello”) is 6?

A string literal is an array of const char that holds its characters and then the terminating null character, '\0'. "hello" is therefore an array of 6 chars, and sizeof measures the whole array: 6 bytes. std::strlen does not know about arrays at all. It receives a pointer to the first character and counts characters until it meets the first '\0', which gives 5. The two also differ after a change: write a '\0' into the middle of a char array and strlen gets shorter, while sizeof stays the size of the array. And inside a function that receives the string as a const char*, sizeof gives the size of the pointer, 8 on a 64-bit computer, which is why only strlen can measure a C string there.

The interviewer may then hand you a bigger buffer, or ask how std::string gets by without counting. Both follow-ups are below, with a reason under every option:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: char buf[32] = "hello"; What are sizeof(buf) and std::strlen(buf)?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: 32 and 5

    The size of an array and the length of the text in it are different numbers. The initialisation copies the five letters and fills the remaining 27 chars with zeros, so strlen finds the terminator at index 5.

  2. Question 2 of 2 Follow-up: how can std::string give its length in one step when std::strlen has to walk?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It stores its size beside the characters, so size() only reads that number

    A std::string keeps its size, and still ends its characters with '\0' for c_str(). A C string keeps only the terminator, so its length must be found by walking to it, on every call.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    A C library offers size_t get_device_name(char* buf, size_t size), which writes at most size - 1 characters and a '\0', and returns the full name's length, like snprintf. Write std::string device_name() around it, and explain what can go wrong.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    const char* display_name(const User& u) { std::string name = u.first + " " + u.last; return name.c_str(); } In a debug build, short names usually print correctly and long names print garbage; in a release build both are often wrong. Explain each observation and fix the function.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A C string is chars followed by '\0'. std::strlen walks to that byte every time it is called, and it counts bytes: "café" is 5.
  • String literals are arrays of const char in read-only memory: point to them with const char*, and writing into one crashed both builds.
  • Compare text with std::strcmp(a, b) == 0. == compares addresses, and == between two arrays is an error in C++26.
  • std::strcpy and std::strcat never check the destination’s size; a 22-byte greeting in a 16-byte buffer gave a crash with Clang, silent damage with GCC and a stack-buffer-overflow report with AddressSanitizer.
  • std::snprintf never overflows, always terminates the text and returns the length it needed.
  • std::string stores its length, manages its memory and compares with ==; c_str() lends a C string that dies with the string or changes with it.

Terms in this lesson

buffer overflow
Writing or reading past the end of a block of memory, as std::strcat does when its destination is too small. The extra bytes land on whatever lies next to the buffer: undefined behaviour, and a classic security hole. AddressSanitizer names it, for example a stack-buffer-overflow.
string literal
Text in double quotes in the source, such as "pune": an array of const char holding the characters and a terminating '\0', made before the program starts and kept for its whole run. Writing into one is undefined behaviour.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.