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