string to char ptr?

Started by
3 comments, last by Cornstalks 12 years, 6 months ago
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;
}
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).
It "works" and has no observable effect because you don't use t.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

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;
}

[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.
[size=2][ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

This topic is closed to new replies.

Advertisement