Jump to content
  • Advertisement
Sign in to follow this  
nuclear123

string to char ptr?

This topic is 2613 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

does this even work and also does it have undefiend behavior?

#include <string>
using namespace std;

int main()
{
string s = "bob";
const char *t = s.c_str();
return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
It works, and is what c_str is for. The buffer returned by c_str() is owned by the s object, so you can't access it beyond the lifetime of s (or after calling any non-const function on s).

Share this post


Link to post
Share on other sites

It "works" and has no observable effect because you don't use t.


Nah, it's perfectly fine, you could print out t and it would work exactly as expected. But what latent said is very legit, once s goes out of scope, t is going to be undefined.

So, this code will cause an undefined behavior, but sadly won't explode, so it will be a bitch to track down.



#include <string>
using namespace std;


const char * GetString()
{
string s = "bob";
return s.c_str();
}

int main()
{
printf("%s",GetString());
return 0;
}



While this code would be perfectly fine, as s persists:




#include <string>
using namespace std;


const char * GetString(string & str)
{
return str.c_str();
}

int main()
{
string s = "bob";
printf("%s",GetString(s));
return 0;
}

Share this post


Link to post
Share on other sites

[quote name='iMalc' timestamp='1319177105' post='4874931']
It "works" and has no observable effect because you don't use t.


Nah, it's perfectly fine, you could print out t and it would work exactly as expected.
[/quote]

I think what he meant is that it "works" as in it's perfectly well defined and valid C++ code, but it accomplishes absolutely nothing so it doesn't really "work," in the sense of accomplishing something.

But yeah, what Serapth said is a perfect example of the quirks of C++ that make it so easy to introduce a bug that is so bloody hard to track down. It's valid, but just be careful how you do it.

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.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!