In a C++ URL builder, why is the pointer from (base + path).c_str() unsafe to give a C API that keeps it?
answer
- whose buffer is it?
- end of the full-expression
- keeps versus copies
- append may reallocate
- which members never invalidate
basics
~20 sc_str() points into the string's own buffer. The temporary base + path dies at the end of its full-expression, so a C API that stores the pointer later reads freed memory. Keep the std::string alive while C uses it.
solid answer
~40 s`c_str()` does not copy anything: it returns a `const char*` into the buffer the `std::string` owns. `base + path` creates a temporary `std::string`, and a temporary dies at the end of the full-expression, the `;`. If the C function only reads the text during the call, that is fine. If it **keeps** the pointer, every later use reads a freed buffer: undefined behaviour that AddressSanitizer reports as `heap-use-after-free`. The pointer from a named string is also fragile: any non-const member call other than `operator[]`, `at`, `data`, `front`, `back`, `begin`, `end`, `rbegin` and `rend`, such as `+=` or `reserve`, may reallocate and invalidate it. The fix is ownership: store the `std::string` beside the C handle that uses it, finish building before calling `c_str()`, and never modify it while the C side holds the pointer.
code
cpp · 15 lines#include <cstdio>
#include <string>
// Stands in for a C networking API that keeps the pointer it is given.
static const char* g_saved_url = nullptr;
extern "C" void net_set_url(const char* url) { g_saved_url = url; }
extern "C" void net_send() { std::printf("GET %s\n", g_saved_url); }
std::string base() { return "https://example.com"; }
int main() {
std::string path = "/api/v1/players/42/inventory";
net_set_url((base() + path).c_str()); // the temporary dies at the ';'
net_send(); // reads freed memory: undefined behaviour
}go deeper
Know that c_str() points into the string's own buffer and is not a copy, so the pointer cannot outlive the string.
Explain when the temporary dies, which operations reallocate the buffer, and why a C API that copies is safe while one that stores is not.
Show how you would catch it with AddressSanitizer and fix it structurally, by tying the string's lifetime to the C handle that uses it.
Treat every pointer handed across the C boundary as a lifetime contract to document and review, because the compiler cannot see the C side's storage.
## What c_str() actually returns `std::string::c_str()` returns a `const char*` pointing at the first character of the string's **own buffer**; the buffer always has a `'\0'` at position `size()`, so the result is a valid C string. `data()` returns the same pointer. Nothing is copied and nothing is allocated, which is why the call is constant time and `noexcept`. The price is that the pointer is a **borrow**: it is valid only while the `std::string` object is alive and its buffer has not been replaced. ## The temporary in the URL builder A URL builder often joins a base and a path and hands the result to a C networking library: ```cpp net_set_url((base() + path).c_str()); // the temporary std::string dies at the ';' net_send(); // reads the freed buffer ``` `base() + path` is a **temporary**. A temporary lives until the end of the **full-expression** that created it, here the whole statement. So the pointer is valid during `net_set_url` and dangling the moment that call returns. Whether this is a bug depends entirely on the C function's contract: - **It copies the text during the call** (many APIs document that they duplicate the string): passing a temporary's `c_str()` is fine. - **It stores the pointer for later**: the next use is **undefined behaviour**. The program may print the right URL for months, because the freed memory still holds the old bytes, and then fail when the allocator reuses that block. AddressSanitizer turns the silent case into a loud one; built with `-fsanitize=address`, the snippet below stops with `ERROR: AddressSanitizer: heap-use-after-free` and shows the `~basic_string` destructor that freed the buffer. ## What else invalidates the pointer Even a named string can pull its buffer out from under you. The standard says references, pointers and iterators into a `basic_string` may be invalidated by: 1. passing the string as a non-const reference to a standard library function, such as `swap`, `operator>>` or `std::getline`; 2. calling any non-const member function **except** `operator[]`, `at`, `data`, `front`, `back`, `begin`, `rbegin`, `end` and `rend`. So `url += "/inventory"`, `url.reserve(256)`, `url.clear()`, `url.shrink_to_fit()` and assigning a new value can all invalidate a pointer taken earlier. Appending is the classic trap: if the new length exceeds the capacity, the string allocates a larger buffer, copies the characters and frees the old one. ## Why it often seems to work Use-after-free bugs of this shape survive testing because nothing checks the pointer. After the temporary's destructor runs, the freed block usually still holds the old characters until the allocator hands it to someone else, so a test that sends the request at once prints the right URL. The failure appears later and somewhere else: under load, after an unrelated allocation, or in a release build with a different allocation pattern. A short URL can behave differently again, because with the small-string optimization its characters may never have been on the heap at all. The reliable detector is a sanitizer build in CI, not a passing test. ## Safe patterns at the C boundary - **Finish building, then borrow.** Do all the `+=` work first and call `c_str()` last, right where the C function is called. - **Make the lifetime explicit.** If the C library keeps the pointer, store the `std::string` in the same object that owns the C handle, declared so it outlives the handle, and never modify it while the handle exists. - **Let the C side copy.** When the API offers a copying variant, prefer it. - **Remember embedded nulls.** A `std::string` may contain `'\0'` characters; the C function stops at the first one, so text from untrusted input can be silently truncated. - **Writable buffers.** Since C++17, non-const `data()` returns `char*`, so a C function may write into `[data(), data() + size())`; writing the terminator to anything but `'\0'` is undefined behaviour. ## A rule to say out loud A pointer from `c_str()` is valid until the string is destroyed or modified by an invalidating operation, whichever comes first. A temporary is destroyed at the end of its statement, so its `c_str()` may be used inside that statement and never stored.
- Is f((a + b).c_str()) ever correct?Yes, when `f` only uses the pointer during the call. The temporary `std::string` lives until the end of the full-expression, which includes the whole call to `f`, so reading or copying the text inside `f` is safe. It becomes a bug only when `f` stores the pointer for use after it returns, which is a question about the C function's documented contract.
- Does calling c_str() itself ever invalidate earlier pointers into the string?No. `c_str()` and `data()` are const members that return the existing buffer, and since C++11 they may not invalidate iterators or pointers. C++03's rules allowed them to; the standard's compatibility annex lists `data` and `c_str` among the const members that no longer invalidate, and the terminator must now be present at all times.
- How would you keep a URL alive for a C library handle that stores the pointer?Make one C++ object own both: a `std::string url_` member declared before the handle member, so it is constructed first and destroyed last, and the constructor passes `url_.c_str()` to the C API. Never modify `url_` afterwards; changing the URL means building a new string and re-registering it, then releasing the old one only after the C side has switched.
- c_str() returns a fresh copy that stays valid on its own.
- A temporary std::string lives until the end of the enclosing function.
- Appending to a string never moves its existing characters.
- If the program printed the right URL, the pointer must be valid.
- Only destroying the string can invalidate a pointer from c_str().