const char* getName()
{
return obj->getName().c_str(); // g_obj->getName returns std::string
}
It is called from C so I cant return std::string. How can I return a C string without memory problems?
C strings and memory problems
I have a function that is implemented in C++ like this (Not actual implementation. Just an example of what I'm tying to do.)
What memory problems are you reffering to? AFAIK, you can safely perform read-only operartions on returned in such a way string, and nothing will be leaked. Of course, if you want to write, you have to copy it - but that's logical, isn't it? :-)
obj->getName returns a std::string that is destroyed when the function returns. If I try to read from the C string the program crashes.
If you know that the calling C code will (or can be made to) free the string you return when it is no longer needed then just return strdup(blah.c_str()). Otherwise you'll have to redesign your code so that you return a c_str() of a std::string that has a longer lifetime, just like you'd have to if you weren't dealing with std::string objects at all and had to return a valid char const[].
Enigma
Enigma
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement