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

I am writing a string class similar to std :: string for homework, but I cannot figure out how to return a c-string that does not cause a memory leak, and is guaranteed to remain unchanged until it is no longer used. 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 redefined soon after its call. If I perform dynamic allocation, I will either have a memory leak, or only one c-string can exist from the given string at any time. How can i avoid this?

+5
source share
3 answers

, c_str, , std::string ( ).

( , ). , c_str O (1); .

+7

The buffer returned by c_str () does not guarantee that it will remain the same or even valid until it is no longer used.

It is guaranteed to remain valid until std :: string is changed in any way.

The implementation is straightforward: just save the internal representation of the zero-terminated string at any time and return a pointer to the internal representation from c_str ().

0
source

All Articles