Topic: oststream behavior
Author: kcline@sun132.dsccc.com (Kevin Cline)
Date: 1995/05/01 Raw View
What should the following function return? A null pointer,
or a pointer to a zero byte on the heap?
char *f() {
ostrstream s;
return s.str();
}
Kevin Cline
--
Kevin Cline
Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1995/05/01 Raw View
In article 95May1113506@sun132.dsccc.com, kcline@sun132.dsccc.com (Kevin Cline) writes:
>What should the following function return? A null pointer,
>or a pointer to a zero byte on the heap?
>
>char *f() {
> ostrstream s;
> return s.str();
>}
Either, or neither. The str() function is allowed to return a null
pointer. If the pointer it returns is not null, there is never a
guarantee that the string it points to is null-terminated, unless you
write a null to the string yourself. Example:
ostrstream s;
s << "hello";
char* p = s.str(); // not necessarily null-terminated
The C++ draft standard has dropped strstreams in favor of stringstreams,
which do not suffer from these ambiguities.
---
Steve Clamage, stephen.clamage@eng.sun.com
Author: pstaite@powertool.rchland.ibm.com (Philip Staite)
Date: 1995/05/01 Raw View
In article <KCLINE.95May1113506@sun132.dsccc.com>, kcline@sun132.dsccc.com (Kevin Cline) writes:
|> What should the following function return? A null pointer,
|> or a pointer to a zero byte on the heap?
|>
|> char *f() {
|> ostrstream s;
|> return s.str();
|> }
Maybe. You'll either get a null pointer or a pointer to valid storage (but not necessarily a null terminated string) and a potential memory leak. According to the S. Teale's "C++ IO Streams Handbook" the str() function "freezes" a dynamically allocated buffer within an ostrstream. However, if the stream has never had any put()s against it str() may return null. Once str() is called the dynamic buffer is frozen and must be unfrozen before the stream is destructed or you must delete[] the storage.
If the ostrstream has preallocated some space then you'll get a non null pointer. However, there is no guarantee that this is a zero length string or null terminated. You need to use the ends manipulator for that...
--
Phil Staite
pstaite@vnet.ibm.com