- Handle realloc failure without leaking memory

(reported by: grendel@heorot.stanford.edu (Ted U)
- Don't cast malloc/realloc/calloc return values because they hide LP64 bugs.
- Don't destroy the whole array when realloc fails
- Use calloc in all cases (malloc was used inconsistently).
- Avoid duplicating code.

Reviewed by: ross
This commit is contained in:
christos 2001-05-12 19:21:57 +00:00
parent 6f62797262
commit 00adbfd8d6
1 changed files with 18 additions and 28 deletions

View File

@ -1,4 +1,4 @@
/* $NetBSD: ip_fil.c,v 1.66 2001/03/26 06:13:12 mike Exp $ */
/* $NetBSD: ip_fil.c,v 1.67 2001/05/12 19:21:57 christos Exp $ */
/*
* Copyright (C) 1993-2000 by Darren Reed.
@ -9,7 +9,7 @@
*/
#if !defined(lint)
#if defined(__NetBSD__)
static const char rcsid[] = "$NetBSD: ip_fil.c,v 1.66 2001/03/26 06:13:12 mike Exp $";
static const char rcsid[] = "$NetBSD: ip_fil.c,v 1.67 2001/05/12 19:21:57 christos Exp $";
#else
static const char sccsid[] = "@(#)ip_fil.c 2.41 6/5/96 (C) 1993-2000 Darren Reed";
static const char rcsid[] = "@(#)Id: ip_fil.c,v 2.42.2.17 2000/10/19 15:39:42 darrenr Exp";
@ -1706,6 +1706,8 @@ char *name;
int v;
{
struct ifnet *ifp, **ifa;
size_t len;
# if (defined(NetBSD) && (NetBSD <= 1991011) && (NetBSD >= 199606)) || \
(defined(OpenBSD) && (OpenBSD >= 199603))
for (ifa = ifneta; ifa && (ifp = *ifa); ifa++) {
@ -1722,33 +1724,21 @@ int v;
}
# endif
if (!ifneta) {
ifneta = (struct ifnet **)malloc(sizeof(ifp) * 2);
if (!ifneta)
return NULL;
ifneta[1] = NULL;
ifneta[0] = (struct ifnet *)calloc(1, sizeof(*ifp));
if (!ifneta[0]) {
free(ifneta);
return NULL;
}
nifs = 1;
} else {
nifs++;
ifneta = (struct ifnet **)realloc(ifneta,
(nifs + 1) * sizeof(*ifa));
if (!ifneta) {
nifs = 0;
return NULL;
}
ifneta[nifs] = NULL;
ifneta[nifs - 1] = (struct ifnet *)malloc(sizeof(*ifp));
if (!ifneta[nifs - 1]) {
nifs--;
return NULL;
}
len = (nifs + 2) * sizeof(*ifa);
ifa = ifneta == NULL ? malloc(len) : realloc(ifneta, len);
if (ifa == NULL)
return NULL;
ifp = ifa[nifs] = calloc(1, sizeof(*ifp));
if (ifa[nifs] == NULL) {
if (nifs == 0)
free(ifa);
return NULL;
}
ifp = ifneta[nifs - 1];
ifneta = ifa;
ifneta[++nifs] = NULL;
# if (defined(NetBSD) && (NetBSD <= 1991011) && (NetBSD >= 199606)) || \
(defined(OpenBSD) && (OpenBSD >= 199603))