Where does the pointer returned by calling string::c_str() point to ? In the following code snippet, I thought I will give get a segmentation fault but it gives me the corre
Where does the pointer returned by calling
string::c_str()
point to?
It points to some place in memory where a null-terminated string containing the contents of the std::string
is located.
The pointer is only valid until the std::string
is modified or destroyed. It is also potentially invalidated if you call c_str()
or data()
again.
Basically, your safest bet is to assume the pointer obtained from c_str()
is invalidated the next time you do something to the std::string
object.
I should get an invalid memory access.
No, you get undefined behavior. You might get a memory access error of some kind (like a segmentation fault), but your program also might appear to continue running correctly. It might appear to work one time you run your program but fail the next.