Make sure we free the buffer in all error cases.

Do the final realloc(3) to the size of the string, not the size of the buffer
allocated for the string (which is a noop).
This commit is contained in:
mycroft 1998-10-15 07:36:09 +00:00
parent 285284da77
commit ef3079f0ee
2 changed files with 34 additions and 33 deletions

View File

@ -1,4 +1,4 @@
/* $NetBSD: asprintf.c,v 1.2 1998/09/08 14:13:36 kleink Exp $ */
/* $NetBSD: asprintf.c,v 1.3 1998/10/15 07:36:09 mycroft Exp $ */
/*
* Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
@ -29,7 +29,7 @@
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: asprintf.c,v 1.2 1998/09/08 14:13:36 kleink Exp $");
__RCSID("$NetBSD: asprintf.c,v 1.3 1998/10/15 07:36:09 mycroft Exp $");
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
@ -61,24 +61,26 @@ asprintf(str, fmt, va_alist)
#else
va_start(ap);
#endif
f._file = -1;
f._flags = __SWR | __SSTR | __SALC;
f._bf._base = f._p = (unsigned char *)malloc(128);
if (f._bf._base == NULL) {
*str = NULL;
errno = ENOMEM;
return (-1);
}
if (f._bf._base == NULL)
goto err;
f._bf._size = f._w = 127; /* Leave room for the NUL */
ret = vfprintf(&f, fmt, ap);
if (ret == -1)
goto err;
*f._p = '\0';
va_end(ap);
_base = realloc(f._bf._base, f._bf._size + 1);
if (_base == NULL) {
errno = ENOMEM;
ret = -1;
}
f._bf._base = _base;
*str = (char *)f._bf._base;
_base = realloc(f._bf._base, ret + 1);
if (_base == NULL)
goto err;
*str = (char *)_base;
return (ret);
err:
if (f._bf._base)
free(f._bf._base);
*str = NULL;
errno = ENOMEM;
return (-1);
}

View File

@ -1,4 +1,4 @@
/* $NetBSD: vasprintf.c,v 1.2 1998/09/08 14:13:36 kleink Exp $ */
/* $NetBSD: vasprintf.c,v 1.3 1998/10/15 07:36:09 mycroft Exp $ */
/*
* Copyright (c) 1997 Todd C. Miller <Todd.Miller@courtesan.com>
@ -29,7 +29,7 @@
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: vasprintf.c,v 1.2 1998/09/08 14:13:36 kleink Exp $");
__RCSID("$NetBSD: vasprintf.c,v 1.3 1998/10/15 07:36:09 mycroft Exp $");
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
@ -46,26 +46,25 @@ vasprintf(str, fmt, ap)
FILE f;
unsigned char *_base;
f._file = -1;
f._flags = __SWR | __SSTR | __SALC;
f._bf._base = f._p = (unsigned char *)malloc(128);
if (f._bf._base == NULL) {
*str = NULL;
errno = ENOMEM;
return (-1);
}
if (f._bf._base == NULL)
goto err;
f._bf._size = f._w = 127; /* Leave room for the NUL */
ret = vfprintf(&f, fmt, ap);
if (ret == -1)
goto err;
*f._p = '\0';
_base = realloc(f._bf._base, f._bf._size + 1);
if (_base == NULL) {
if (f._bf._base)
free(f._bf._base);
f._bf._base = NULL;
errno = ENOMEM;
ret = -1;
}
f._bf._base = _base;
*str = (char *)f._bf._base;
_base = realloc(f._bf._base, ret + 1);
if (_base == NULL)
goto err;
*str = (char *)_base;
return (ret);
err:
if (f._bf._base)
free(f._bf._base);
*str = NULL;
errno = ENOMEM;
return (-1);
}