Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does c_str() method from string class returns?

Tags:

c++

I want to access starting address of the array that is maintained by the string class.

string str="hey";
char* pointer=(char*)str.c_str();
  1. Is the pointer pointing to the address of the array(maintained by the string class)? or string class will create a new array from dynamic memory and copy the existing string into it and return it's address?

  2. If this is not the right way, then how to access the starting address of the array that is maintained by the string class?

like image 807
Amit Bhaira Avatar asked Jul 01 '13 11:07

Amit Bhaira


1 Answers

In C++11 standard it's explicitly stated that .c_str() (as well as newer .data()) shall return pointer to the internal buffer which is used by std::string.

Any modification of the std::string after obtaining the pointer via .c_str() may result in said char * returned to became invalid (that is - if std::string internally had to reallocate the space).

In previous C++ standards implementation is allowed to return anything. But as standard do not require user to deallocate the result, I've never seen any implementation returning anything newly allocated. At least GNU gcc's and MSVC++'s STL string are internally zero-terminated char arrays, which are returned by c_str().

So it's safe to assume (with normal for C++ caution) that in any version of C++ in any it's implementation .c_str() will return internal buffer.

In other words - you should never ever keep the value of the .c_str() unless you are 100% sure it's won't change it's size anytime in future (unless it's a const, that is).

P.S. BTW, you should never ever do char* pointer=(char*)str.c_str();. It's const char * and you shall not modify the contents, partly because the above - you may end-up overwriting memory of some other object or corrupting internal state of std::string, in case implementation doing something fancy, like indexing characters for faster .find()(newer seen that, but hey - that's an encapsulation!)

like image 157
Andrian Nord Avatar answered Sep 28 '22 15:09

Andrian Nord