Skip to main content
GameDev.net gamedev.net
🔒 Locked

C strings and memory problems

Started by mike25025 Sep 11, 2005 at 6:46 PM 3 replies 950+ views
Original Post
mike25025
mike25025
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?
mike25025
mike25025
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.
Enigma
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()). 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
mike25025
mike25025
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]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.