Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::string::c_str() return a c-string that does not cause a memory leak or undefined c-string contents?

I'm writing a string class that is similar to std::string for a homework assignment, but I cannot figure out how to return a c-string that does not cause a memory leak and is guaranteed to stay the same until it is no longer in use. I currently have:

const char* string::c_str()
{
    char c[_size+1];
    strncpy(c,_data,_size);
    c[_size]='\0';
    return c;
}

but the contents are overridden shortly after it is called. If I do dynamic allocation, I'll have either a memory leak or only one c-string can exist from a given string at any time. How can I avoid this?

like image 325
Jakob Weisblat Avatar asked Jul 04 '12 23:07

Jakob Weisblat


2 Answers

But the string pointed to by c_str is only well-defined until the std::string is next modified (or destroyed).

One way to achieve this might be simply to return a pointer to your internal buffer (assuming it's null-terminated). Bear in mind that a standards-compliant c_str has to operate in O(1) time; so copying is not permitted.

like image 93
Oliver Charlesworth Avatar answered Sep 28 '22 09:09

Oliver Charlesworth


From http://www.cplusplus.com/reference/string/string/c_str/:

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only guaranteed to remain unchanged until the next call to a non-constant member function of the string object.

like image 20
reuben Avatar answered Sep 28 '22 10:09

reuben