Jump to content
  • Advertisement
Sign in to follow this  
mike25025

C strings and memory problems

This topic is 4815 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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? :-)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!