Subject: Memory leak in setenv(3) ?
To: #List NetBSD current users <current-users@NetBSD.ORG>
From: Paul Goyette <>
List: current-users
Date: 05/29/2003 18:45:16
I've been looking for a while to find a memory leak in one of my
programs, and I think I've finally narrowed things down to, of all
things, setenv(3) (and unsetenv(3), too)!

It seems that if you set an environment variable, _and_ you have the
overwrite flag set, it will reuse the existing value's space if and
only if the new value is  not longer than the old value.

In all other cases (new value is longer, overwrite not set, or no
previous value exists), a new chunk of memory is malloc(3)d;  if there
was a previous value, it is conveniently forgotten without ever being
free(3)d!  Similarly, if you unsetenv(3) a variable, the value is just
discarded without being free(3)d.

Granted, this probably wouldn't affect too many people, since one
usually doesn't keep redefining the same environment variable over and
over.  But in my case, I have a server that needs to fairly frequently
display timestamps to users that connect, and each user has his/her
own TZ value.  So, in order to make localtime(3) use the correct TZ, I
need to continually update the environment variable.

Wouldn't it make sense that, if we're going to use malloc(3) to get
space for the environment variables, we would properly use realloc(3)
and free(3) to keep track of space no longer being used by them?

Just as an aside, we _do_ use malloc(3) and realloc(3) to manage the
list of pointers to environment variable values!   :)

|   Paul Goyette   | PGP DSS Key fingerprint: |  E-mail addresses:   |
| Network Engineer | 9DC5 05CF 1AE7 DC42 CCC6 |   |
|  & World Cruiser | 6858 051E 7AD2 A6B2 4954 | |