1 /* Replacement for a missing setenv.
3 ** Written by Russ Allbery <rra@stanford.edu>
4 ** This work is hereby placed in the public domain by its author.
6 ** Provides the same functionality as the standard library routine setenv
7 ** for those platforms that don't have it.
16 setenv(const char *name, const char *value, int overwrite)
20 if (!overwrite && getenv(name) != NULL)
23 /* Allocate memory for the environment string. We intentionally don't
24 use concat here, or the xmalloc family of allocation routines, since
25 the intention is to provide a replacement for the standard library
26 function which sets errno and returns in the event of a memory
27 allocation failure. */
28 envstring = malloc(strlen(name) + 1 + strlen(value) + 1); /* __MEM_CHECKED__ */
29 if (envstring == NULL)
32 /* Build the environment string and add it to the environment using
33 putenv. Systems without putenv lose, but XPG4 requires it. */
34 strcpy(envstring, name); /* __STRCPY_CHECKED__ */
35 strcat(envstring, "="); /* __STRCAT_CHECKED__ */
36 strcat(envstring, value); /* __STRCAT_CHECKED__ */
37 return putenv(envstring);
39 /* Note that the memory allocated is not freed. This is intentional;
40 many implementations of putenv assume that the string passed to
41 putenv will never be freed and don't make a copy of it. Repeated use
42 of this function will therefore leak memory, since most
43 implementations of putenv also don't free strings removed from the
44 environment (due to being overwritten). */