How to use a static environment
Giuseppe Modugno
giuseppe.modugno.loqed@gmail.com
Fri Apr 6 07:27:00 GMT 2018
Il 05/04/2018 18:28, Craig Howland ha scritto:
> 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.
What happens when I set TZ back to CET? setenv() calls again malloc(),
because "GMT0" (old value) is shorter than "CET..." (new value).
More information about the Newlib
mailing list