ostrstream question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • becte

    #1

    ostrstream question

    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?
  • Victor Bazarov

    #2
    Re: ostrstream question

    becte wrote:[color=blue]
    > 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();[/color]

    You're returning a property of an object about to be destroyed.
    [color=blue]
    > }
    >
    > int main ()
    > {
    > static char *p1 = NULL, *p2 = NULL;
    > p1 = func(1);[/color]

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

    Same problem here. p2 is invalid.
    [color=blue]
    > 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.[/color]

    Right.
    [color=blue]
    > 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?[/color]

    No.

    V

    Comment

    Working...