Using environment variables without leaking memory?

Rich Felker dalias at aerifal.cx
Thu Oct 26 13:09:07 PDT 2006


On Thu, Oct 26, 2006 at 10:43:06AM -0400, Rob Landley wrote:
> On Wednesday 25 October 2006 6:20 pm, Dave Dodge wrote:
> > On Tue, Oct 24, 2006 at 03:51:35PM -0400, Rob Landley wrote:
> > > because what if somebody did a getenv() and kept the pointer around after 
> > > doing an unsetenv()?
> > 
> > Then they're broken by definition.  POSIX/SUS explicitly says that the
> > getenv results can be damaged by getenv, setenv, or unsetenv (but by
> > no other library function).
> > 
> > If you're willing to make broken programs break, you can probably
> > implement the environment stuff without too much pain.  putenv is
> > perhaps the worst of it, though somewhat ironically the rationale for
> > keeping it in the Standard was that it's the only guaranteed way to
> > avoid memory leaks.
> 
> That makes no sense.  If the guaranteed way to avoid leaks is to track the 
> memory you feed to putenv() and free it after doing an unsetenv(), then you 
> still can't free it afterwards if "damaged" might include freed.  If the 

Damaged cannot include freed because the implementation cannot know
where it came from. It might be from malloc, or static memory, or
mmap, or even const memory in the text segment. Things like
putenv("TZ=UTC0"); are pretty common.

Moreover nothing says that the string passed to putenv can be damaged.
Rather, it says the results of getenv cannot be expected to survive
putenv/setenv/unsetenv. That is to say, the implementation may just
strdup() anything you pass to putenv, and then free it later, even
though it's free to use the original you passed it. Stupid, huh? :(

> standard just says you can modify the memory, then to make it longer you have 
> to realloc() it, which can move it...
> 
> It still sounds just plain mis-designed from the ground up...

Yes. Or rather, it never was designed. :(

Rich



More information about the uClibc mailing list