How to use a static environment

Craig Howland howland@LGSInnovations.com
Thu Apr 5 16:28:00 GMT 2018


On 04/05/2018 10:49 AM, Giuseppe Modugno wrote:
> I need to use environment functionality in newlib to have a correct result 
> from localtime() with the western european timezone (I need TZ environment 
> variable). I  also need to convert UTC struct tm to time_t with mktime(), so I 
> should delete TZ variable before calling mktime().
>
> I know I can call setenv()/unsetenv(), but I would like to avoid using dynamic 
> allocation (that those functions use). So I'm thinking to have two static 
> const environments, such as:
>
>   static const char *const env_with_tz[] = { "TZ=CET-1CEST,M3.5.0,M10.5.0/3", 
> NULL };
>   static const char *const env_empty[] = { NULL };
>
> and change the environment on-the-fly in the following way:
>
>   extern char **environ;
>   environ = env_with_tz;        // or environ = env_empty;
>
> Is it safe?
>
> Of course I need to call tzset() before calling mktime()/localtime() if the 
> environment has changed.
>
>
Are you trying to avoid the dynamic allocation of set/unset at all, or only when 
changing the TZ value?  The reason for asking is that you can avoid it in the 
latter case very easily.  This is because setenv() does not free or allocate if 
a new string fits in the space taken by the prior value, and just overwrites the 
value (when the overwrite flag is set).  So you can set 
TZ=CET-1CEST,M3.5.0,M10.5.0/3, then (rather than unsetting it), set TZ=GMT0.  
Then set it back to CET again.
Craig



More information about the Newlib mailing list