1 /* $Id: setenv.c 5713 2002-09-01 03:04:10Z rra $
3 ** Replacement for a missing setenv.
5 ** Written by Russ Allbery <rra@stanford.edu>
6 ** This work is hereby placed in the public domain by its author.
8 ** Provides the same functionality as the standard library routine setenv
9 ** for those platforms that don't have it.
15 /* If we're running the test suite, rename setenv to avoid conflicts with
16 the system version. */
18 # define setenv test_setenv
19 int test_setenv(const char *, const char *, int);
23 setenv(const char *name, const char *value, int overwrite)
27 if (!overwrite && getenv(name) != NULL)
30 /* Allocate memory for the environment string. We intentionally don't
31 use concat here, or the xmalloc family of allocation routines, since
32 the intention is to provide a replacement for the standard library
33 function which sets errno and returns in the event of a memory
34 allocation failure. */
35 envstring = malloc(strlen(name) + 1 + strlen(value) + 1);
36 if (envstring == NULL)
39 /* Build the environment string and add it to the environment using
40 putenv. Systems without putenv lose, but XPG4 requires it. */
41 strcpy(envstring, name);
42 strcat(envstring, "=");
43 strcat(envstring, value);
44 return putenv(envstring);
46 /* Note that the memory allocated is not freed. This is intentional;
47 many implementations of putenv assume that the string passed to
48 putenv will never be freed and don't make a copy of it. Repeated use
49 of this function will therefore leak memory, since most
50 implementations of putenv also don't free strings removed from the
51 environment (due to being overwritten). */