setenv/unsetenv's known memory leak

Dag-Erling Smørgrav des at des.no
Wed Feb 23 09:06:28 GMT 2005


Seán C. Farley <sean-freebsd at farley.org> writes:
> While playing around with setenv(), I noticed that it can leak memory
> when a program overwrites a variable with a larger value.  unsetenv()
> will just leak memory.  All of this is documented in their man pages.
>
> The latest PR on this (two PR's mentioned in it are closed):
> http://www.freebsd.org/cgi/query-pr.cgi?pr=misc/19406

They were closed for a reason.  Read their audit trails.

> I could find no apparent reason for continuing to allow for the memory
> leak.  The only reason given to allow it was to permit programs to
> continue to use the environment variable retrieved by setenv() after the
> program had reset or deleted it.

Wrong.  The reason for the leak is that the initial environment array
is not malloc()ed and therefore cannot be free()d or realloc()ed.  To
work around this requires a lot of bookkeeping.

BTW, SUSv3 explicitly states that the application can not expect the
pointer returned by getenv() to remain meaningful after a subsequent
call to getenv(), setenv(), unsetenv() or (on XSI-conformant systems)
putenv(), so that argument falls flat on its face.

> Here is a test program along with a patch to stop the leak:
> http://www.farley.org/freebsd/tmp/setenv.tar.bz2

You can't possibly have tested it very thoroughly.  Try running your
test program with MALLOC_OPTIONS=AX in your environment:

des at xps ~/src/setenv% MALLOC_OPTIONS=AX ./testenv
testenv in realloc(): error: junk pointer, too high to make sense
zsh: abort (core dumped)  MALLOC_OPTIONS=AX ./testenv

DES
-- 
Dag-Erling Smørgrav - des at des.no


More information about the freebsd-hackers mailing list