On Wed, 23 Feb 2005, Dag-Erling Smørgrav wrote:

Seán C. Farley <[EMAIL PROTECTED]> 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.

Thank you. That is good to know.

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:

[EMAIL PROTECTED] ~/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

That is odd. I do not see that error with my changes (old or new) and using MALLOC_OPTIONS. I am running 5-STABLE.

I have made a new set of patches based on your and Peter Jeremy's
comments (variables on the stack).  The first patch is just style
changes.  The second patch is the actual change.  They were tested with
MALLOC_OPTIONS=AX and dmalloc (not at the same time).  The changes are:
1. Tracking of dynamically allocated environment variables.
2. Reallocation/freeing of variables using above tracking to prevent
   incorrect manipulation of variables allocated on the stack.

http://www.farley.org/freebsd/tmp/setenv.tar.bz2

How does this version look?

Seán
--
[EMAIL PROTECTED]
_______________________________________________
freebsd-hackers@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
To unsubscribe, send any mail to "[EMAIL PROTECTED]"

Reply via email to