--- setenv.c.orig	Thu Feb 24 18:49:43 2005
+++ setenv.c	Thu Feb 24 18:49:43 2005
@@ -40,9 +40,12 @@
 #include <stddef.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/types.h>
 
 char *__findenv(const char *, int *);
 
+static uint8_t dynamicEnv = 0;			/* Env vars were copied */
+
 /*
  * setenv --
  *	Set the value of the environmental variable "name" to be
@@ -59,6 +62,18 @@
 	char *c;
 	int l_value, offset;
 
+	/*
+	 * Make copies of environment variables to allow for
+	 * reallocation.  This stops a potential memory leak
+	 * when resetting a variable with larger values.
+	 */
+	if (!dynamicEnv) {
+		for (offset = 0; environ[offset]; offset++)
+			if ((environ[offset] = strdup(environ[offset])) == NULL)
+				return (-1);
+		dynamicEnv = 1;
+	}
+
 	if (*value == '=')			/* no `=' in value */
 		++value;
 	l_value = strlen(value);
@@ -94,7 +109,7 @@
 	}
 	for (c = (char *)name; *c && *c != '='; ++c);	/* no `=' in name */
 	if (!(environ[offset] =			/* name + `=' + value */
-	    malloc((size_t)((int)(c - name) + l_value + 2))))
+	    reallocf(environ[offset], (size_t)((int)(c - name) + l_value + 2))))
 		return (-1);
 	for (c = environ[offset]; (*c = *name++) && *c != '='; ++c);
 	for (*c++ = '='; (*c++ = *value++); );
@@ -113,8 +128,11 @@
 	char **p;
 	int offset;
 
-	while (__findenv(name, &offset))	/* if set multiple times */
+	while (__findenv(name, &offset)) {	/* if set multiple times */
+		if (dynamicEnv)
+			free(environ[offset]);
 		for (p = &environ[offset];; ++p)
 			if (!(*p = *(p + 1)))
 				break;
+	}
 }

