C strings and memory problems

Started by
3 comments, last by mike25025 18 years, 8 months ago
I have a function that is implemented in C++ like this (Not actual implementation. Just an example of what I'm tying to do.)
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?
Advertisement
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
Quote:Original post by Enigma
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()).
I think Ill do that. Thank you for your help.

[Edited by - mike25025 on September 11, 2005 7:06:21 PM]

This topic is closed to new replies.

Advertisement