Leaking is nasty, but I have to agree with Ed here.
The problem with Graham's "proper" solution is that it is quite legitimate for a pure-C caller -- e.g. a DSO with no knowledge of APR whatsoever -- to pull an environment variable with getenv and expect to be able to hold on to that pointer for the lifetime of the program.
Awful, but true. API fail!
Here's what the BSD folks have to say, courtesy of my Leopard box:
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 indefi-
nitely) make this bug unavoidable. Future versions may eliminate one or both of these semantic guarantees in order to fix the
It's pretty much the same everywhere else IME.
- Windows automatically copies and controls the memory with _putenv, allocating a copy on Windows should not be done.
- Unix requires a memory allocation, you can free the memory in the environment if you clear the environment variable.
In my opinion it is not worth the coding effort to keep track of the environment variables you set and then freeing them. Environment variables should be set once and used for the life of the program they are not meant to be set and unset over and over again.
UNIX should just be putenv(strdup("FOO=abc"));//set it and forget it.
From: Graham Leggett [mailto:firstname.lastname@example.org]
Sent: Monday, March 29, 2010 9:55 AM
To: Dan Poirier
Subject: Re: apr_env_set use of putenv
On 29 Mar 2010, at 3:36 PM, Dan Poirier wrote:
> I don't think that's the right pattern to follow. apr_table is used
> allocate a new data structure, owned by the caller, and the caller
> certainly should control its lifetime. apr_env_set() is used to add
> entry to the OS's environment, which the caller does not own and would
> not expect to have any control over the lifetime of its entries.
From what I can see of the code right now, the caller is expected to
control the lifetime of the string that it passes, or set up their own
cleanup as appropriate to ensure that the environment entry is removed
if the pool is removed.
The strdup() is by definition a leak, so that isn't ideal at all.
I suspect the docs would need to be updated to warn the caller than if
they set a string in the environment, they are required to ensure
their string lives as long as the process, or to register their own
cleanup if not.