How to use a static environment

Bob Dunlop bob.dunlop@xyzzy.org.uk
Thu Apr 5 16:34:00 GMT 2018


On Thu, Apr 05 at 05:46, Giuseppe Modugno wrote:
> Il 05/04/2018 17:32, Bob Dunlop ha scritto:
> > Hi,
> >
> > I don't know the newlib specifics but have played with this in other
> > library environments before.
> >
> > The answer to your first question "Should unsetenv() free?" the
> > answer is No because unsetenv() doesn't know where the original string
> > came from.  You could be freeing something that was never malloc'd.
> setenv() calls malloc to copy and save the new variable/value pair in a 
> single string. So I was thinking the behaviour of unsetenv() should be 
> symmetrical, i.e. unsetenv() should have free. Otherwise:
> 
>  ? setenv("TZ", "whatever", 1);
>  ? unsetenv("TZ");
> 
> and you will have a memory leak... right?

Yes you have a memory leak.  It's even documented in the Glibc putenv man
page, you either accept a memory leak or violate SUSv2.

Also as I said before you don't have a clue where the original environment
value came from.  In my early Unix days exec() set it up on the top of stack
like it was auto variables in the function that called main().  Think I saw
a system once that passed it as a special data segment/page.  I've certainly
seen embedded systems where the initial values were in ROM and the pointer
array built on the fly, pointing at the ROM until changes were made.


Problem is to find the lowest common denominator of the different libraries
and platforms.  How about:

  static char tzbuf[] = "TZ=Value_long_enough_for_any_we_want_to_set";
  char *tzbuf_value;

  /* Need to clear any previous string as we don't know where it's been.
   * This is probably a one off memory leak.
   */
  unsetenv("TZ");

  /* Set our buffer although library may take a malloc'd copy */
  setenv( tzbuf );
  /* Find the value buffer location (either our original or the copy) */
  tzbuf_value = getenv("TZ");

  strcpy( tzbuf_value, "UTC0" );
  etc...


Should work unless you have a system that stores the environment as a single
buffer "key1\0value1\0key2\0value2\0\0" and shuffles the buffer up and down
as you expand/contract the individual values.  A 1980's embedded system if
I recall correctly.

-- 
        Bob Dunlop



More information about the Newlib mailing list