Skip to content
systemcoding.dev
Systems Programming

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.

1 min read
Summarize in AI

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.

envdefault.cc
#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;
}
Text
$ ./envdefault
port = 8080
$ PORT=9000 ./envdefault
port = 9000
$ PORT= ./envdefault
port = 8080

The 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).

Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.