Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 26 Sep 2002 02:16:17 -0400
From:      Barney Wolff <barney@tp.databus.com>
To:        stable@freebsd.org
Subject:   Re: [v]asprintf leaks memory
Message-ID:  <20020926061617.GA16599@tp.databus.com>
In-Reply-To: <20020925155222.GA4874@tp.databus.com>
References:  <20020925133219.GA59210@HAL9000.homeunix.com> <20020925155222.GA4874@tp.databus.com>

next in thread | previous in thread | raw e-mail | index | archive | help
There is possibly a more serious bug here.  If vfprintf returns with
f._bf._base NULL, it would seem that *f._p = '\0'; will store
into freed memory.  Perhaps harmless, but that assumes a particular
malloc implementation.  What's more, if the reallocf actually switches
buffers, the 0 may not have been copied, and may have been beyond the end of
the original buffer.  If vfprintf always leaves room for the 0, the
reallocf call is never necessary.  I think safer code would read:

	ret = vfprintf(&f, fmt, ap);
	va_end(ap);
	if (f._bf._base != NULL) f._bf._base = reallocf(f._bf._base, ret + 1);
	if (f._bf._base != NULL) f._bf._base[ret] = '\0';
	else {
		errno = ENOMEM;
		ret = -1;
	}
	*str = (char *)f._bf._base;
	return ret;
}

Barney

On Wed, Sep 25, 2002 at 06:32:19AM -0700, David Schultz wrote:
> Index: src/lib/libc/stdio/asprintf.c
> ===================================================================
> RCS file: /home/ncvs/src/lib/libc/stdio/asprintf.c,v
> retrieving revision 1.6
> diff -u -u -r1.6 asprintf.c
> --- src/lib/libc/stdio/asprintf.c	1999/08/28 00:00:55	1.6
> +++ src/lib/libc/stdio/asprintf.c	2002/09/25 13:08:48
> @@ -71,7 +71,8 @@
>  	ret = vfprintf(&f, fmt, ap);
>  	*f._p = '\0';
>  	va_end(ap);
> -	f._bf._base = reallocf(f._bf._base, f._bf._size + 1);
> +	if (f._bf._base != NULL)
> +		f._bf._base = reallocf(f._bf._base, f._bf._size + 1);
>  	if (f._bf._base == NULL) {
>  		errno = ENOMEM;
>  		ret = -1;

-- 
Barney Wolff
I'm available by contract or FT:  http://www.databus.com/bwresume.pdf

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-stable" in the body of the message




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