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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With