C++ Basics: Distinguish String Size from C-String Length
Growing a std::string with resize adds null characters by default. They count toward size even though a C-string function stops at the first null.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as string-resize-null-padding-demo.cpp:
#include <cstring>
#include <iostream>
#include <string>
int main()
{
std::string label{"AB"};
label.resize(5);
std::cout << "size=" << label.size()
<< ", c-length=" << std::strlen(label.c_str()) << '\n';
std::cout << std::boolalpha << "padding is null: "
<< (label[2] == '\0' && label[3] == '\0' && label[4] == '\0') << '\n';
label.resize(2);
label.resize(5, '.');
std::cout << "visible padding: " << label << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-resize-null-padding-demo.cpp -o string-resize-null-padding-demo &&
./string-resize-null-padding-demoObserved output:
size=5, c-length=2
padding is null: true
visible padding: AB...Read the result
The grown string has five elements but a C-string length of two. Shrinking removes the null padding; growing with an explicit dot character makes the added elements visible.
Apply it carefully
reserve changes capacity without adding elements; resize changes size. Embedded nulls are valid string elements. When transferring binary-like data, pass the explicit size to an API that accepts it. A C-string API cannot infer data after an embedded null. The terminating null supplied by c_str is separate from the size elements.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- string-resize-null-padding-demo.cpp string-resize-null-padding-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.