Using environment variables without leaking memory?

Rob Landley rob at landley.net
Mon Oct 23 20:35:06 UTC 2006


On Sunday 22 October 2006 10:13 pm, Paul Brook wrote:
> > How do I set (and reset) environment variables without leaking memory?  I
> > _think_ if I use setenv() instead of putenv() it won't leak memory 
(freeing
> > the old one), but if I previously used putenv() and then call setenv() to
> > update that variable, does it free the old chunk of memory?  Or not?  (How
> > does it know?  Presumably the environment variables inherited from a 
parent
> > process weren't allocated with malloc()...)
> 
> When you create a new process the kernel makes a new copy of the 
environment. 
> Usually this is put at the top of the new process' stack. The environment is 
> not shared between multiple processes.

I'd guessed that part (although I can't find anywhere it's explicitly stated, 
other than by you just now).  But right now I'm writing a shell and this can 
set and reset the same environment variables multiple times (for loops, etc).  
When I assign a value to a variable, how do I know if the previous value is 
going to get freed or not?  If I use putenv, I think I have to maintain a 
list of all the variables I set and search it to free the old one each time I 
set a new one.  (And don't free it if it's not in the list because you don't 
free variables you inherited from exec, I guess they just leak.)

Presumably if I use setenv() it creates copies of stuff and I don't have to 
worry about freeing them, and it's not confused by variables that live in the 
heap and variables from exec (which aren't in the heap, but in some kind of 
environment space)...

If the answer is "use setenv, it handles all this for you" I'm ok with that...

> Paul

Rob
-- 
"Perfection is reached, not when there is no longer anything to add, but
when there is no longer anything to take away." - Antoine de Saint-Exupery



More information about the uClibc mailing list