This is the mail archive of the
newlib@sourceware.org
mailing list for the newlib project.
Re: How to use a static environment
- From: Bob Dunlop <bob dot dunlop at xyzzy dot org dot uk>
- To: Giuseppe Modugno <giuseppe dot modugno dot loqed at gmail dot com>
- Cc: newlib at sourceware dot org
- Date: Thu, 5 Apr 2018 16:32:18 +0100
- Subject: Re: How to use a static environment
- References: <b7b2c56f-7d1b-1932-a60c-6306f445db0d@gmail.com>
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.
I'd also expect if it did free the memory you'd find a lot of use after
free bugs pop out of the wooodwork.
On Thu, Apr 05 at 04:49, 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?
I doubt it very much.
putenv() should be you friend rather than setenv() since it installs
a string that you are then allowed to manipulate.
static char tzbuf[ 50 ];
/* Install your buffer */
/* Your string may only be installed if the slot is empty */
unsetenv("TZ");
strcpy(tzbuf, "TZ=CET-1CEST,M3.5.0,M10.5.0/3");
putenv(tzbuf);
/* No need to call putenv() any more */
/* From now on you just need to manipulate the value in tzbuf */
strcpy(tzbuf + 3, "CET-1CEST,M3.5.0,M10.5.0/3");
Action using TZ
strcpy(tzbuf + 3, "UTC0")
Action using TZ...
--
Bob Dunlop