Read an environment variable with a default fallback in C
getenv returns NULL for an unset variable and an empty string for a set-but-empty one, so test both before falling back to a default.
Reading a setting from the environment with a fallback takes one more check than most programs make. getenv returns NULL when the variable is absent, but it returns a pointer to an empty string when the variable is set to nothing, as PORT= ./server does. Treating the empty string as unset avoids a confusing atoi("") of zero.
#include <stdio.h>
#include <stdlib.h>
static const char *env_or(const char *name, const char *fallback)
{
const char *v = getenv(name);
return (v && *v) ? v : fallback;
}
int main(void)
{
printf("port = %s\n", env_or("PORT", "8080"));
return 0;
}$ ./envdefault
port = 8080
$ PORT=9000 ./envdefault
port = 9000
$ PORT= ./envdefault
port = 8080The returned pointer points into the environment itself, so a later setenv, putenv or unsetenv may invalidate it; copy the string with strdup if you keep it. Never write through it. For programs that run with elevated privilege, glibc 2.17 added secure_getenv, which returns NULL in setuid and setgid processes, so an attacker cannot steer a privileged program with LD_* style variables. The semantics are in getenv(3).