Topic: OSTRSTREAM and sizing
Author: James Kanze US/ESC 60/3/141 #40763 <kanze@lts.sel.alcatel.de>
Date: 1996/02/26 Raw View
In article <4glkpb$c8q@engnews1.Eng.Sun.COM> clamage@Eng.sun.com
(Steve Clamage) writes:
|> In article sfr@venus.roc.csci.csc.com, tottinge@csci.csc.com (Tim Ottinger) writes:
|> >This might be a silly question, but a coworker of mine noticed this, and we've
|> >tested it on two compilers with similar results:
|> > #include <iostream.h>
|> > #include <strstream.h>
|> > int main (char * argc, char * argv[])
|> > {
|> > ostrstream str("abcdefg", 4);
|> >
|> > cout << "Length = " << str.pcount() << endl;
|> > cout << "Data = " << str.str();
|> > }
|> >produces the following output on both the GNU and HP C++ compilers
|> > Length = 0
|> > Data = abcdefg
|> >Two things were puzzling about this.
|> >The first was that the length parameter on the c'tor didn't seem
|> >to be used for anything, and the second was that I couldn't spot the
|> >right way to tell how big the buffer in the strstreambuf is (how many
|> >actual characters are in it).
|> In the example code, you create an ostrstream, and pass in a fixed
|> buffer. You tell the ostrstream that the buffer can hold 4 characters,
|> including a terminating null, if any. You don't write anything to
|> the stream.
Just one small point which Steve forgot to mention (since it wasn't
really relevant to the question you asked): you'd better not try and
write anything to this stream, either, since it will result in
attempting to modify a string literal (undefined behavior according to
the standard, a segment violation in better compilers).
An interesting question: is ostrstream allowed to modify the parts of
the buffer which are presumed unwritten? Could a legal implementation
of ostrstream, for example, start by zapping the buffer to '\0'? If
this is the case, the above example invokes undefined behavior even
without writing to the stream.
(It's worth noting that in Steve's example of how to correctly use the
functions, the buffer is declared explicitly as an array, in order to
avoid the undefined behavior.)
--
James Kanze Tel.: (+33) 88 14 49 00 email: kanze@gabi-soft.fr
GABI Software, Sarl., 8 rue des Francs-Bourgeois, F-67000 Strasbourg, France
Conseils, tudes et r alisations en logiciel orient objet --
-- A la recherche d'une activit dans une region francophone
---
[ comp.std.c++ is moderated. To submit articles: Try just posting with your
newsreader. If that fails, use mailto:std-c++@ncar.ucar.edu
comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
Comments? mailto:std-c++-request@ncar.ucar.edu
]