Using environment variables without leaking memory?
Dave Dodge
dododge at dododge.net
Tue Oct 24 07:45:40 PDT 2006
On Sun, Oct 22, 2006 at 09:08:58PM -0400, Rob Landley wrote:
> Maybe this is the wrong place to ask, but the fundamental problem is
> that the libc API is badly designed.
One of the difficulties is that at the pure C level all you have is
getenv and there is no portable way to change the environment at all.
Things like putenv and environ are all extensions that have been added
by various implementations over the years. POSIX/SUS tries to keep
most of those mechanisms available simultaneously for backwards
compatibility, even when it would be arguably cleaner to deprecate
them. Add threads into the mix and it just gets worse.
> How do I set (and reset) environment variables without leaking memory?
The preferred API is getenv, setenv, and unsetenv. I don't think
there's any guarantees about them freeing memory, but their API does
at least allow them to do so.
Other stuff gleaned from various bits of POSIX/SUS:
While not explicitly forbidden, applications should not use environ or
envp for lookups. I'm not sure there's any other way to iterate over
the environment, though.
Applications must not use environ directly to make modifications. One
reason is that the implementation is explicitly allowed to maintain
multiple copies of the environment data internally, such as a hash
table to speed up getenv.
When multithreaded, using environ directly for any purpose while some
thread is modifying the environment causes undefined behavior. You
must further assume that any library function dependent on an
environment setting will use environ directly.
None of the environment-related functions are guaranteed reentrant.
Environment variable names should not start with a digit.
-Dave Dodge
More information about the uClibc
mailing list