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_stris only well-defined until thestd::stringis 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_strhas to operate in O(1) time; so copying is not permitted.