Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 3 Aug 2003 23:12:32 -0700
From:      David Schultz <das@FreeBSD.ORG>
To:        "Ryan T. Dean" <rtdean@cytherianage.net>
Cc:        freebsd-current@FreeBSD.ORG
Subject:   Re: vfprintf() has a 4096-byte memory leak?
Message-ID:  <20030804061232.GA873@HAL9000.homeunix.com>
In-Reply-To: <3F2BAC6B.3040606@cytherianage.net>
References:  <3F2BAC6B.3040606@cytherianage.net>

next in thread | previous in thread | raw e-mail | index | archive | help
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.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20030804061232.GA873>