C++ Basics: Check a String Search Before Slicing
Check std::string::find against npos before using the result as an offset. A missing separator must take a different path from a separator at position zero.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus 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-find-npos-guard-demo.cpp:
#include <iostream>
#include <string>
int main()
{
for (const std::string line : {"mode=fast", "missing", "=empty-key"}) {
auto separator = line.find('=');
if (separator == std::string::npos) {
std::cout << "no separator\n";
continue;
}
std::cout << "key=[" << line.substr(0, separator)
<< "] value=[" << line.substr(separator + 1) << "]\n";
}
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic string-find-npos-guard-demo.cpp -o string-find-npos-guard-demo &&
./string-find-npos-guard-demoObserved output:
key=[mode] value=[fast]
no separator
key=[] value=[empty-key]Read the result
The first line splits normally. The missing separator is handled explicitly, and a separator at zero produces an empty key instead of being mistaken for failure.
Apply it carefully
Do not test a search offset as a boolean: zero is a valid position. Do not add one to npos and then slice; npos is an unsigned sentinel and arithmetic can wrap. Decide separately whether empty keys, empty values or repeated separators are allowed. This example splits only at the first equals sign and does not implement escaping or a full configuration format.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- string-find-npos-guard-demo.cpp string-find-npos-guard-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.