Why I don’t have to free string from c_str function of std::string? How the function generate const char* and how it be destroyed?
Asked
Active
Viewed 338 times
1
-
Recommended reading: [What is meant by Resource Acquisition is Initialization (RAII)?](https://stackoverflow.com/questions/2321511/what-is-meant-by-resource-acquisition-is-initialization-raii). Less topical, but still important: [What is The Rule of Three?](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three) – user4581301 Dec 01 '19 at 08:14
-
@user4581301 How will any of those help the OP understand how it is they don't need to free the **raw pointer** returned by `c_str`? – user4815162342 Dec 01 '19 at 08:19
-
Does this answer your question? [What is std::string::c\_str() lifetime?](https://stackoverflow.com/questions/6456359/what-is-stdstringc-str-lifetime) – user4815162342 Dec 01 '19 at 08:21
-
RAII link explains the philosophy behind why they don't have to free the memory. The Rule of Three is just tacked on as a supplemental because it explains and solves a common problem that almost all new C++ programmers hit once they start applying RAII (and then usually try to solve with `new`). – user4581301 Dec 01 '19 at 08:24
-
@user4581301 *RAII link explains the philosophy behind why they don't have to free the memory* RAII itself doesn't answer the OP's question because `c_str()` returns a raw pointer. See the posted answer for an example of an answer that does address the question. – user4815162342 Dec 01 '19 at 09:28
-
Does this answer your question? [Does a pointer returned by std::string.c\_str() or std::string.data() have to be freed?](https://stackoverflow.com/questions/7460753/does-a-pointer-returned-by-stdstring-c-str-or-stdstring-data-have-to-be) – imz -- Ivan Zakharyaschev Feb 19 '20 at 18:22
-
@user4815162342 If you still believe this Q is a duplicate, then vote again please. So that this doesn't age away. – imz -- Ivan Zakharyaschev Jul 29 '21 at 19:41
1 Answers
3
The const char*
return from c_str()
is managed by the std::string
itself, and is destroyed when the std::string
goes out of date. In this regard, one must be careful they don't attempt to use the pointer returned from c_str()
after the std::string
is destroyed:
const char* getName()
{
std::string name = "Joe";
return name.c_str();
}
The above is wrong, because when name
is destructed as getName
returns, the pointer will become invalid.

Tas
- 7,023
- 3
- 36
- 51
-
I remember earlier versions of the C++ spec said that `std::string` **could** be non-contiguous in memory (C++11 changed it to require that it be contiguous). What would the `c_str()` data look like if it was a pre-C++11 non-contiguous string? – Dai Dec 01 '19 at 08:06
-
@Dai In that case the string implementation would have been expected to store the pointer to the data returned by `c_str` and free it in the destructor. – user4815162342 Dec 01 '19 at 08:11