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?
source
share