Index of /freebsd/tmp/setenv/setenv-6

[ICO]NameLast modifiedSizeDescription

[DIR]Parent Directory   -  
[DIR]regression/ 19-Apr-2007 00:03 -  
[   ]setenv-6.tar.bz2 19-Apr-2007 00:03 8.9K 
[TXT]sysenv.c 19-Apr-2007 00:03 10K 
[   ]sysenv.patch 19-Apr-2007 00:03 12K 
[DIR]tests/ 19-Apr-2007 00:03 -  

Fixing setenv/unsetenv()'s memory leaks

PR: bin/99826

When writing code to use a third-party library, I ran into a leak that setenv() exhibits when overwriting a variable with a larger value. Calling unsetenv() will just leak memory. All of this is documented in the man page (setenv(3)):

Successive calls to setenv() or putenv() assigning a differently sized value to the same name will result in a memory leak. The FreeBSD semantics for these functions (namely, that the contents of value are copied and that old values remain accessible indefinitely) make this bug unavoidable. Future versions may eliminate one or both of these semantic guarantees in order to fix the bug.

Unfortunately, I must reset an environment variable quite a lot resulting in a quick memory leak.

To prevent the leak, I have written a patch which copies the entire environment into dynamic memory upon the first setenv() or unsetenv(). This way any time an existing variable has its value updated with a larger value the old value is freed and replaced with a new copy. unsetenv() will free values if setenv() has been called first. This was tested with dmalloc and MALLOC_OPTIONS=AX.

Note: this does not patch the man page to remove the note about the memory leak.