Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ostream manage memory?

Tags:

c++

ios

ostream

Compared to std::string and std::ofstream which do allocate memory on the heap, programs containing std::cout don't seem to have any heap allocation. I know that std::ostreams inherit xalloc, iword and pword. The latter two have descriptions that they do have some sort of memory management.

First, allocates or resizes the private storage (dynamic array of long or another indexable data structure) sufficiently to make index a valid index, then returns a reference to the long element of the private storage with the index index.

But valgrind seems to indicate that there isn't any heap allocation.

  1. When does this allocation/resizing occur?
  2. Do the std::ostreams internal use new and delete or malloc and free?
like image 534
user4039902 Avatar asked Jun 14 '26 07:06

user4039902


1 Answers

A std::ostream is a base class that lets derived classes hook into its std::streambuf. So, a std::ostream can be seen as a wrapper around a std::streambuf pointer (along with a pointer to it's locale and formatting information).

The std::streambuf is in itself a base class with a heap of virtual functions that does not in itself allocate memory - derived classes do when they implement it. For example std::filebuf which implements the stream buffer of a std::fstream, allocates the buffer for file I/O.

As far as I know, buffered I/O (using iostream or not) allocates memory on the heap for its buffer, including std::cout. The buffer of the standard output stream is allocated very early (before main) and in all cases. So, your program won't use more or less memory when you do or do not use std::cout. At least on GNU/Linux using libstdc++6. It is possible that other implementations use special buffers that are allocated in a different way.

like image 73
Carlo Wood Avatar answered Jun 16 '26 21:06

Carlo Wood