Re: vfprintf() has a 4096-byte memory leak?

From: David Schultz <das_at_FreeBSD.ORG>
Date: Sun, 3 Aug 2003 23:12:32 -0700
On Sat, Aug 02, 2003, Ryan T. Dean wrote:
> "Poul-Henning Kamp" wrote:
> >In message <3F2B9C59.3060209 at cytherianage.net 
> ><http://lists.freebsd.org/mailman/listinfo/freebsd-current>>, "Ryan T. 
> >Dean" writes:
> >>/Hey all-
> /> >/    I was doing some app debugging tonight, and noticed what appears 
> to /> >/be a memory leak in vfprintf().
> /> 
> >This is probably the buffer which stdio uses for all I/O.
> >
> >Try calling 
> >	setbuf(stdout, NULL);
> >	setbuf(stderr, NULL);
> >
> >as the very first thing in your program, and you will probably see
> >that it does not allocate the 4k buffer, you may also be able to
> >measure the performance change due to this.
> >
> >In other words, what you see is perfectly normal, and to be expected,
> >but if it is a problem for you, the above is the workaround.
> 
> Aha.  setbuf(stdout, NULL); does prevent the buffer from being allocated.
> However, in the case of stdout and stderr, if you don't setbuf() it to 
> null, a buffer is malloc'd.  The corresponding free() is in fclose.  So, if 
> you [f]printf() to stdout/stderr, and fclose(stdout/stderr), you are fine.  
> If, however, you don't know that buffers are being allocated for 
> stdin/stdout and don't fclose() or setbuf() to NULL, a 4096-byte chunk of 
> memory is allocated and never freed.  For shits and giggles, I checked a 
> DeadRat 8 box - no buffering by default.  I guess the only reason I'm 
> worried is the
> potential number of programs in the ports tree originally written on a 
> system
> where stdout/stderr behave differently, or people (like myself) who didn't
> have a clue any sort of output buffering was enabled on stdout/stderr, and 
> as a result have memory leaks.  If the porter did their job, it shouldn't 
> be an issue (was caught, patched, and the patch submitted upstream), but, 
> then, we never know, right?

stdio's buffering routines make a one-time allocation for their
buffers, and this memory does not get freed because it can
potentially get used during the entire time the program is
running.  This isn't a bug.  See the archives for details.
Received on Sun Aug 03 2003 - 21:12:53 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:37:17 UTC