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