ostrstream question

B

becte

I encountered the following code similar to this
// some header files
static char* func(int i)
{
ostrstream out;

if (i==1) out << "ABCDE";
else if (i==2) out << "123";
else cout << "";

return out.str();
}

int main ()
{
static char *p1 = NULL, *p2 = NULL;
p1 = func(1);
p2 = func(2);
printf ("String1 = %s, String2 = %s\n", p1, p2);
return 0;
}
The desired out put is "String1 = ABCDE, String2 = 123".
New if I used an character array, char out[10], and returning &out[0]
instead of ostrstream this would definitly be illegal.
But this looks illegal too, I suppose ostrstream has some destructor
that deletes any allocated memory. What is confusing is that this
happens to work when i try it. Is this legal after all?
 
V

Victor Bazarov

becte said:
I encountered the following code similar to this
// some header files
static char* func(int i)
{
ostrstream out;

if (i==1) out << "ABCDE";
else if (i==2) out << "123";
else cout << "";

return out.str();

You're returning a property of an object about to be destroyed.
}

int main ()
{
static char *p1 = NULL, *p2 = NULL;
p1 = func(1);

p1 here is invalid because it contains a pointer value to a buffer of
a stream that is no more.
p2 = func(2);

Same problem here. p2 is invalid.
printf ("String1 = %s, String2 = %s\n", p1, p2);
return 0;
}
The desired out put is "String1 = ABCDE, String2 = 123".
New if I used an character array, char out[10], and returning &out[0]
instead of ostrstream this would definitly be illegal.
Right.

But this looks illegal too, I suppose ostrstream has some destructor
that deletes any allocated memory. What is confusing is that this
happens to work when i try it. Is this legal after all?

No.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top