TITLE: safely deleting a stream str() buffer (Newsgroups: comp.lang.c++.moderated, 8 Aug 98) XAVIER: Xavier Huet >>Simon Gornall wrote: >>> On an SGI (in case it makes a difference) the manual pages don't >>> really make it clear what to call in order to dispose of memory >>> that has been obtained by calling the str() method of a dynamically >>> allocating ostrstream. CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) >The safe way to release the memory is to invoke the strstreambuf >function "freeze" with parameter 0. That directs the stream to >unlock the memory and to delete it automatically when the stream >is destroyed. If you retain a pointer to the buffer after the >stream is destroyed, there is no guaranteed safe way to >release the memory. > >Most likely > delete [] ptr; >will work, but it isn't guaranteed. CLAMAGE: clamage@Eng.Sun.COM Following up my own post, using delete is not safe. The memory in use for the buffer might have been passed in to the ostrstream constructor. If so, the delete is likely to be disastrous. If you unfreeze the buffer, the ostrstream destructor will delete the buffer automatically if and only if the buffer was allocated by the ostrstream class itself. If you try to unfreeze a buffer that was not allocated by the ostrstream, the attempt will silently be ignored. Unfreezing the buffer is thus always safe and correct. Examples: #include int main() { ostrstream vs; // variable length vs << "Hello"; char* s = vs.str(); // ... use s vs.rdbuf()->freeze(0); // no longer use s // buffer will be deleted when vs goes out of scope char buf[100]; ostrstream fs(buf, 100); // fixed length vs << "hello"; char *t = fs.str(); // ... use t delete [] t; // tries to delete a non-heap object! fs.rdbuf()->freeze(0); // has no effect, and so is safe }