Returning c_str from a function
Posted
by user199421
on Stack Overflow
See other posts from Stack Overflow
or by user199421
Published on 2010-04-17T04:03:19Z
Indexed on
2010/04/17
4:13 UTC
Read the original article
Hit count: 272
This is from a small library that I found online:
const char* GetHandStateBrief(const PostFlopState* state)
{
static std::ostringstream out;
... rest of the function ...
return out.str().c_str()
Now in my code I am doing this:
const char *d = GetHandStateBrief(&post);
std::cout<< d << std::endl;
Now, at first d contained garbage. I then realized that the c string I am getting from the function is destroyed when the function returns because std::ostringstream is allocated on the stack. So I added:
return strdup( out.str().c_str());
And now I can get the text I need from the function.
I have two questions:
1) Am I understanding this correctly?
2) I later noticed that the ostringstream was was allocated with static storage. Doesn't that mean that the object is supposed to stay in memory until the program terminates? and if so , then why can't I access the string?
© Stack Overflow or respective owner