Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string::c_str() allowed to allocate anything on the heap?

Tags:

c++

string

If I need to get a NUL-terminated char array out of a std::string in a situation where I need to be sure nothing will be allocated, is it safe to use c_str to do so? For example, if I'm inside a destructor and I want to copy some data from a string into a pre-allocated, fixed-size buffer, can I use c_str and be sure it won't throw anything?

like image 399
Pillsy Avatar asked Sep 29 '10 15:09

Pillsy


2 Answers

The standard says that calling c_str() may invalidate references, pointers, and interators referring to the elements of the string, which implies that reallaocation is permitted (21.3/5 "Class template basic_string").

You might want to just call string::copy() to get your copy (you'll need to add the null terminator yourself if you need it).

like image 158
Michael Burr Avatar answered Nov 15 '22 17:11

Michael Burr


No, the standard gives no such guarantee. The only guarantee in the C++ standard is that the returned value points to a char array with the same contents as the std::string, plus a nul-terminator.

So it would be standards-conforming for an implementation to store its internal representation in some way other than a C-string, and allocate a C-string on the fly when you call c_str, although I'm fairly certain that no widely used STL implementation actually does this.

Now, with respect to C++0x, I have heard (although I am at a loss for finding documentation for this at the moment), that one of the changes is going to be to require that std::string operate on contiguous storage (a similar requirement already exists for std::vector). So in that case, you could access the span from &str[0] through &str[0]+str.length()-1 as if it were a C-string without a nul-terminator.

like image 28
Tyler McHenry Avatar answered Nov 15 '22 18:11

Tyler McHenry