Why is passing std::string_view::data() to a C function such as std::atoi or std::fopen a bug in C++?
answer
- C finds the end by scanning
- the view ends by length
- the neighbour's characters
- %.*s or a copy
- from_chars takes a range
basics
~20 sA string_view ends by its length, so data() need not be null-terminated. A C function scans for '\0' and reads past the view, giving wrong results or undefined behaviour. Pass a terminated std::string copy or use pointer-and-length APIs.
solid answer
~50 sA `std::string_view` marks its end with a stored length; C functions such as `std::atoi`, `std::strtol`, `std::fopen` or `printf("%s")` find the end by scanning for `'\0'`. The standard even notes that `data()` can point at a buffer that is not null-terminated and that passing it to a function expecting a terminated string is typically a mistake. Three outcomes follow. A view of a whole `std::string` or literal happens to work. A view of part of a larger buffer reads the following characters: `atoi` on a view of `"12"` inside `"1280"` returns 1280, with no sanitizer able to object. A view into a raw buffer without any terminator reads past its end, undefined behaviour that AddressSanitizer reports as an overflow. Fix it at the boundary: `std::string(sv).c_str()`, `printf("%.*s", int(sv.size()), sv.data())`, `std::from_chars` for numbers, or APIs that take a length.
code
cpp · 17 lines#include <charconv>
#include <cstdlib>
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string header = "Content-Length: 1280";
std::string_view digits = std::string_view(header).substr(16, 2); // the view is "12"
int wrong = std::atoi(digits.data()); // atoi ignores the length: reads "1280"
int right = 0;
std::from_chars(digits.data(), digits.data() + digits.size(), right);
int copied = std::atoi(std::string(digits).c_str()); // terminated copy
std::cout << digits << ' ' << wrong << ' ' << right << ' ' << copied << '\n';
}go deeper
Remember that a string_view ends by its length, not by a '\0', so C functions cannot see where it stops.
Explain why a view of a whole string works by accident and a substring reads its neighbour's characters.
Fix it at the boundary with a terminated copy, %.*s or from_chars, and choose const std::string& for functions that must reach C APIs.
Make the C boundary an explicit layer in the codebase so that terminator assumptions live in one reviewed place instead of scattered data() calls.
## Two ways to mark the end of text C strings end where the first `'\0'` byte is; every C library function that takes a single `const char*`, such as `strlen`, `atoi`, `strtol`, `fopen`, `getenv` or `printf` with `%s`, walks forward until it finds one. A `std::string_view` ends where its **length** says, and the byte after its last character can be anything: the next character of a larger string, the next field of a network packet, or memory the program does not own. `std::string` guarantees a terminator at `data() + size()`. `std::string_view` does not, and the standard says so in a note on `data()`: unlike `basic_string::data()` and string literals, it can return a pointer to a buffer that is not null-terminated, so it is typically a mistake to pass it to a function that takes just a `const charT*` and expects a terminated string. ## Three outcomes of the same mistake 1. **It works by accident.** The view covers a whole `std::string` or a whole literal, so a terminator happens to follow. Tests pass, and the code is one refactoring away from case 2. 2. **It reads the neighbour's characters.** The view is a slice of a larger buffer. In a header parser, `digits` views `"12"` inside `"Content-Length: 1280"`; `std::atoi(digits.data())` returns **1280**, because `atoi` keeps reading digits past the view. Every byte read belongs to the same live string, so the program is well-defined and wrong, and no sanitizer can flag it. 3. **It reads past the buffer.** The view slices a received chunk stored in a `char` array without a terminator. The C function runs off the end of the array: **undefined behaviour**. On this machine, `std::strlen` on such a view stopped AddressSanitizer with `stack-buffer-overflow`. The second case is the dangerous one in practice: it produces plausible numbers and file names. ## Fixing it at the boundary | need | fix | |---|---| | any C function that takes `const char*` | `std::string(sv).c_str()`: a terminated copy, alive until the end of the statement | | printing | `std::printf("%.*s", static_cast<int>(sv.size()), sv.data())`, or a stream or `std::format`, which honour the length | | parsing a number | `std::from_chars(sv.data(), sv.data() + sv.size(), value)` (C++17), which takes a range | | writing bytes | `std::fwrite(sv.data(), 1, sv.size(), f)` or a POSIX `write` with the length | The copy costs an allocation when the text is longer than the small-string buffer, which is the honest price of crossing into a terminator-based API. ## Where the assumption hides The bug rarely looks like a C call in a code review. Common disguises: - `std::ifstream file(name.data());` where `name` is a view of a path inside a configuration line; - `std::getenv(key.data())` or `std::system(cmd.data())` with a key or command sliced from input; - logging helpers that end in `printf("%s", ...)` or a C logging library; - `std::strtol(field.data(), &end, 10)`, which also scans past the view even though it reports where it stopped. C++ interfaces that accept a view, or a `std::string` built from one, avoid the problem: `std::filesystem::path` can be constructed from a `std::string_view`, and streams and `std::format` print a view by its length. ## Designing APIs that reach C - If a function's implementation must call a C API expecting a terminated string, take `const std::string&` or `const char*` instead of `std::string_view`. Taking a view would force a copy on every call to rebuild the terminator the caller often already had. - If it only reads characters in C++, take `std::string_view`. - Never assume "this view came from a `std::string`, so it is terminated": a later `substr` or `remove_suffix` breaks the assumption without touching this code. - Treat `.data()` of a view passed to a single-pointer parameter as a review finding unless the callee also receives the length. ## The constructor direction too The trap has a mirror image. `std::string_view(const char* p)` computes the length with `char_traits::length`, which is `strlen`, so `p` must point at a terminated string; constructing a view from a non-terminated buffer needs `std::string_view(p, n)`. And since C++23, constructing a view from `nullptr` does not compile, while a null `const char*` variable remains undefined behaviour.
- Is printf("%s", sv.data()) safe when sv views an entire std::string?It prints the right text, because `std::string` keeps a terminator at `data() + size()`, but it is safe only by coincidence. The moment the view is narrowed with `substr` or `remove_suffix`, `%s` prints past its end. Use `printf("%.*s", static_cast<int>(sv.size()), sv.data())`, which bounds the output by the length, so the code stays correct for every view.
- Why does std::from_chars fit string_view better than std::atoi or std::stoi?`std::from_chars` (C++17) takes a `[first, last)` range, so it stops at the view's end instead of scanning for a terminator. It also reports errors through a returned `std::errc`, never throws and never allocates. `std::stoi` needs a `std::string`, so a view must be copied first, and `std::atoi` cannot report errors at all.
- string_view::data() always points at a null-terminated string.
- If the view came from a std::string, passing data() to C is always safe.
- AddressSanitizer will catch every misuse of data() with a C function.
- atoi stops at the end of the view because the view knows its size.
- std::string(sv).c_str() is pointless because sv is already terminated.