Set and Unset Environment Variables with setenv and unsetenv
setenv copies its arguments and honors an overwrite flag, unsetenv removes a name, and putenv stores your pointer. Learn the rules and what children inherit.

A program changes its own environment for one reason: so that the programs it starts next see a different one. Setting LANG=C before running a sorting tool, removing HTTP_PROXY before a local test, pointing TMPDIR at a private directory: all of these are changes to the environment of a process that then passes them to its children. In C the tools are setenv(), unsetenv() and the older putenv(), and the third of them has a memory trap that has bitten generations of programmers. This post shows each call, the overwrite flag, what children inherit, the putenv() bug with its symptom and the return values you should check. It uses C17, GCC 14 and glibc 2.40 on Linux 6.12, and follows setenv(3) and POSIX.1-2024.
What changing the environment can and cannot do
A process owns a private copy of its environment. When it calls setenv(), it changes that copy and nothing else: not its parent, not the shell that launched it and not any process already running. The change takes effect for the process itself (a later getenv() sees it) and for every child started after the call, because a child gets a copy of the environment at the moment it is created. That explains a question that comes up often: a program cannot set a variable in your interactive shell. The shell is a different process with a different copy. Commands like source and eval exist so that the shell itself runs the code that sets the variable.
setenv and the overwrite flag
#include <stdlib.h>
int setenv(const char *name, const char *value, int overwrite);setenv() creates the variable if it does not exist. If it already exists, the third argument decides: a nonzero overwrite replaces the value, and 0 leaves the existing value alone and still returns success. The function copies both name and value into memory it manages, so your strings can live on the stack or be freed immediately after the call.
#include <stdio.h>
#include <stdlib.h>
static void show(const char *name)
{
const char *v = getenv(name);
printf("%s = %s\n", name, v ? v : "(unset)");
}
int main(void)
{
setenv("REGION", "eu-west", 1); /* created */
show("REGION");
setenv("REGION", "us-east", 0); /* exists, overwrite = 0: unchanged */
show("REGION");
setenv("REGION", "us-east", 1); /* exists, overwrite = 1: replaced */
show("REGION");
unsetenv("REGION"); /* removed */
show("REGION");
return 0;
}REGION = eu-west
REGION = eu-west
REGION = us-east
REGION = (unset)The overwrite = 0 form is the right choice for defaults: "set TMPDIR to /var/tmp unless the caller already chose one". With overwrite = 1 you take control. A program that sets defaults should use 0, and one that forces a value for a child should use 1.
What setenv returns
The function returns 0 on success and -1 on failure, with errno set. There are two failures worth knowing. EINVAL means the name is empty or contains an equals sign, since setenv("A=B", "x", 1) would be ambiguous. ENOMEM means the environment could not grow. Checking costs one line and catches the first, which is a real bug when names come from user input:
if (setenv(name, value, 1) == -1) {
perror("setenv");
return EXIT_FAILURE;
}A value may be an empty string, and the variable is then set but empty, which differs from unset. A NULL value is not allowed, so use unsetenv() to remove a variable.
unsetenv
unsetenv(name) removes every entry with that name and returns 0, or -1 with EINVAL for an invalid name. Removing a variable that does not exist is not an error. Remember that the getenv() pointer problem applies: if you called getenv("REGION") earlier and still hold the pointer, calling unsetenv("REGION") makes it dangle.
putenv and its trap
putenv() takes a single string of the form "NAME=value":
int putenv(char *string);The difference from setenv() is ownership. putenv() does not copy the string. It stores your pointer in the environment array, so the environment now points at your memory, and your memory must stay valid and unchanged for as long as the variable exists. A local buffer breaks that rule when the function returns:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void configure(void)
{
char entry[32];
snprintf(entry, sizeof entry, "MODE=%s", "batch");
putenv(entry); /* BUG: stores a pointer to a stack buffer */
}
static void clobber(void)
{
char noise[32];
memset(noise, 'x', sizeof noise); /* reuses the stack the old buffer lived in */
noise[sizeof noise - 1] = '\0';
printf("noise: %.4s...\n", noise);
}
int main(void)
{
configure();
clobber();
printf("MODE = %s\n", getenv("MODE"));
return 0;
}noise: xxxx...
MODE = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxThe exact bytes depend on the compiler and optimization level, so a real run may print garbage, the right value or crash. That unpredictability is the point: the environment holds a pointer to a stack frame that no longer exists, and clobber() reused the same stack space. The fix is setenv("MODE", "batch", 1), which copies. Where you must use putenv(), as with legacy code, allocate the string with malloc() and never free it while it is in the environment. Because glibc replaces a variable when you call setenv() for a name that putenv() put there, the old string is not freed automatically, and reusing a putenv() buffer for a different value leaks or corrupts.
Children inherit the change
The reason for editing the environment is usually a child process. system(), popen(), execvp() and fork() followed by exec all pass the current environment. Here the parent sets two variables, then runs the shell to print them:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
setenv("LANG", "C", 1);
setenv("APP_STAGE", "staging", 1);
unsetenv("HTTP_PROXY");
return system("echo \"LANG=$LANG APP_STAGE=$APP_STAGE HTTP_PROXY=${HTTP_PROXY:-unset}\"");
}env -i HTTP_PROXY=http://proxy.example.test:3128 PATH=/usr/bin:/bin ./child_envLANG=C APP_STAGE=staging HTTP_PROXY=unsetThe program began with a proxy in its environment; unsetenv() removed it before the shell was started, so the child never saw it. The PATH was needed in the test invocation only so that system() could find /bin/sh and echo. A child started with execve() and an explicit envp ignores the parent's environment entirely, which is the stricter option covered in the post on custom environments.
Clearing everything
To remove every variable, POSIX offers no function, but glibc has clearenv(), declared in <stdlib.h> with _DEFAULT_SOURCE. Code that must be portable assigns environ = NULL through extern char **environ; or builds a fresh array for the child. After clearing, add back only what the child needs, such as a fixed PATH:
clearenv();
setenv("PATH", "/usr/bin:/bin", 1);
setenv("LANG", "C", 1);Starting a child from a known minimal environment is the dependable way to get reproducible behavior from external programs, because their behavior otherwise depends on whatever the user had exported.
Rules for the environment
A few habits keep environment code boring:
Use
setenv(), notputenv(), unless you control the string's lifetime.Check the return value, especially when the name comes from outside.
Make all changes before creating threads; the environment is a global with no lock that readers use.
Copy any
getenv()pointer you need after a change.Prefer passing an explicit environment to a child over editing your own, so the parent's behavior does not depend on a side effect.
Setting variables in a loop from a configuration file
A common use is loading NAME=value lines from a file into the environment before launching something. The function below reads such a file, splits each line at the first equals sign and calls setenv() with overwrite off, so variables already set by the caller win over the file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int load_env_file(const char *path)
{
FILE *f = fopen(path, "r");
if (!f)
return -1;
char line[512];
while (fgets(line, sizeof line, f)) {
line[strcspn(line, "\r\n")] = '\0'; /* strip the newline */
if (line[0] == '\0' || line[0] == '#')
continue; /* blank line or comment */
char *eq = strchr(line, '=');
if (!eq || eq == line)
continue; /* malformed: skip */
*eq = '\0';
setenv(line, eq + 1, 0); /* 0: do not override */
}
fclose(f);
return 0;
}Given a file app.env with the lines APP_PORT=9000 and APP_MODE=batch, and a parent that already set APP_PORT=7000, the result is APP_PORT=7000 and APP_MODE=batch. The caller's value wins, which is the usual precedence for configuration: an explicit setting in the shell beats a default from a file. Because setenv() copies, the stack buffer line can be reused for the next line without any lifetime concern, which is exactly what putenv() would have broken.


