TITLE: freezing and stringstreams (Newsgroups: comp.lang.c++.moderated, 1 Jun 97) PARASTATIDIS: Savas Parastatidis > > I am using an ostrstream object as a temporary place for some text that may > (or may not) be printed. The ostrstream object (obj) is created with its > void constructor (dynamic allocation of memory). At some point I want to > copy the contents of the object to an ostream. Currently, I do the > following: > > char *str = obj.str(); > .. > cout << ... << str; > .. > obj.freeze(0); > obj.seekp(0); > > The idea is that the ostrstream has to be cleared and ready to be reused > after its contents has been copied. According to Microsoft's Visual C++ > Reference manual str() creates a char array and freezes the strstrambuf > object used. The manual says that the array has to be deleted by the > programmer and the streambuf unfreezed. CLAMAGE: Steve Clamage Yes, except that "freeze(0)" returns control of the buffer to the stream. The code you show here should work fine. (Note: original strstreams had the freeze function only in the strstreambuf, requiring you to write obj.rdbuf()->freeze(0) The draft standard fixes this omission.) Briefly: The ostrstream creates the char array used as the underlying buffer, and will normally delete it when the stream is destroyed. But if you use the "str" function, the stream has no way of knowing how long you might retain the pointer to that buffer. Consequently, it freezes the buffer -- the buffer will not be extended and will not be automatically be deleted if it is frozen. (The buffer won't be extended because it might have to be moved, leaving you with a dangling pointer.) If you unfreeze the buffer, it reverts to its normal behavior. It can be automatically extended by the ostrstream and will be automatically deleted. You must be sure not to use the pointer you got from "str" after you unfreeze the buffer, since the pointer can become invalid at any time afterward. Strstreams are inconvenient to use because of these memory-management considerations. The draft standard defines stringstreams as a replacement. They use a string type as the underlying buffer, so memory management is taken care of by the string class itself. You never have to worry about dangling pointers or memory leaks, because you use strings instead of char pointers.