Back to C Programming
2026-02-286 min read

22.6.3 Accessing Environment Variables

Learn 22.6.3 Accessing Environment Variables step by step with clear examples and exercises.

Why This Matters

Accessing environment variables is a crucial skill for any C programmer as it allows your programs to interact with the operating system and access important system information. In this lesson, we'll explore how to access environment variables in C programming, understand common mistakes, practice questions, and frequently asked questions.

Importance of Environment Variables

  1. Program Configuration: Environment variables can be used to configure programs without modifying the source code. For example, setting an environment variable can change the location of a database or the maximum size of a log file.
  2. Portability: Environment variables allow your program to work on different operating systems with minimal changes. They provide a way to access system-specific information like the user's home directory or temporary files path.
  3. Debugging and Testing: Environment variables can be used for debugging and testing purposes, such as setting custom values for logging or enabling/disabling certain features.
  4. User Preferences: Environment variables allow users to customize their environment based on their preferences, such as setting a preferred text editor or IDE.

Prerequisites

To understand this lesson, you should already be familiar with the following concepts:

  1. Basic C programming: Variables, functions, loops, and control structures.
  2. Command-line arguments: Accessing command-line arguments in a C program (Lesson 22.6.2).
  3. Standard libraries: Understanding the stdlib.h library, which contains functions for accessing environment variables.
  4. Processes and file system: Basic understanding of processes and file systems to understand how environment variables are stored and accessed.

Core Concept

In C programming, you can access environment variables through the main() function's optional third argument, char *envp[]. This array contains pointers to strings representing the environment variables available to the program. The last element of this array is a null pointer (NULL).

Here's an example that prints all environment variables:

#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
for (int i = 0; envp[i] != NULL; i++) {
printf("%s\n", envp[i]);
}
}

Another method of retrieving environment variables is using the library function getenv(), which is defined in stdlib.h. The getenv() function takes a string argument representing the name of the environment variable and returns its value if it exists, or a null pointer otherwise.

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *home_directory = getenv("HOME");
if (home_directory) {
printf("My home directory is: %s\n", home_directory);
} else {
printf("My home directory is not defined!\n");
}
}

Understanding Environment Variables

Environment variables are named key-value pairs that are stored and managed by the operating system. They can be set, modified, or deleted by users or programs. Each environment variable has a unique name (key) and a corresponding value. Environment variables in C are represented as strings, so you should be aware of string handling functions like strcmp(), strtok(), and others.

Worked Example

Let's write a simple program that prints the current working directory and the user's home directory using both methods described in this lesson.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
char *home_directory = getenv("HOME");
char cwd[4096];
ssize_t len = readlink("/proc/self/cwd", cwd, sizeof(cwd));
if (len > 0) {
cwd[len] = '\0'; // Ensure null-terminated string
printf("Current working directory: %s\n", cwd);
} else {
perror("Error reading current working directory");
}
if (home_directory) {
printf("My home directory is: %s\n", home_directory);
} else {
printf("My home directory is not defined!\n");
}
}

Common Mistakes

  1. Forgetting to check if envp or getenv() returns a non-null value. If you don't check for this, your program may crash or produce unexpected results when the environment variable is not set.
  2. Misunderstanding the format of environment variables. Environment variables in C are represented as strings, so you should be aware of string handling functions like strcmp(), strtok(), and others.
  3. Not handling errors correctly. If an error occurs while reading the current working directory or accessing environment variables, make sure your program provides a useful error message instead of crashing or producing unhelpful output.
  4. Assuming that all systems use the same environment variable names. Some environment variable names may differ between operating systems, so it's important to be aware of these differences when writing portable code.
  5. Not properly freeing memory allocated by getenv() if you are using dynamic memory allocation. This can lead to memory leaks.
  6. Not checking the size of the buffer when reading environment variables or current working directory. If the size is too small, it may result in a buffer overflow, leading to undefined behavior or crashes.
  7. Ignoring case sensitivity. Environment variable names are case sensitive, so you should be aware of this when comparing variable names with strcmp().

Practice Questions

  1. Write a program that prints all environment variables with names starting with "PATH".
  2. Modify the worked example to print the size of the current working directory in bytes.
  3. Write a program that sets an environment variable named MY_VAR and prints its value using both methods described in this lesson.
  4. Write a program that reads the value of the HOME environment variable and changes it to a new directory path.
  5. Write a program that checks if an environment variable exists before attempting to access its value. If the variable doesn't exist, prompt the user for a custom value and set the environment variable accordingly.
  6. Write a program that iterates through all environment variables, sorts them alphabetically, and prints them.
  7. Write a program that creates a new environment variable with a random name and value.
  8. Write a program that removes an existing environment variable by its name.
  9. Write a program that lists all environment variables containing the substring "temp".
  10. Write a program that counts the number of environment variables in total.

FAQ

How can I set an environment variable from my C program?

To set an environment variable, you can use the setenv() function from the stdlib.h library:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *my_var = "Hello World";
setenv("MY_VAR", my_var, 1); // Replace 1 with 0 to overwrite an existing variable
printf("Environment variable MY_VAR is set to: %s\n", getenv("MY_VAR"));
}

What happens if I don't pass the envp argument to the main() function?

If you don't pass the envp argument to the main() function, your program will not have access to environment variables. This means it can only use command-line arguments and standard libraries. However, some operating systems may provide a default set of environment variables that are accessible even if they are not passed to the main() function.

How can I check if an environment variable exists without causing a segmentation fault when it doesn't?

To avoid a segmentation fault when accessing a non-existent environment variable, you should first check if the returned value from getenv() is not null:

char *my_var = getenv("MY_VAR");
if (my_var) {
// Do something with my_var
} else {
// Handle the case where MY_VAR doesn't exist
}

How can I access environment variables in a child process created by fork() or exec()?

When a child process is created using fork(), it inherits a copy of its parent's environment variables. When a new program is executed using exec(), the new program also inherits the environment variables from the calling process. However, if you modify the environment variables in the child process or the newly executed program, these changes will not affect the parent process or other child processes.

How can I access environment variables on Windows using C?

On Windows, environment variables are accessed through the GetEnvironmentVariable() function from the kernel32.dll library. Here's an example:

#include <stdio.h>
#include <windows.h>
int main(void) {
char home_directory[MAX_PATH];
DWORD size = MAX_PATH;
if (GetEnvironmentVariable("HOME", home_directory, &size)) {
printf("My home directory is: %s\n", home_directory);
} else {
printf("My home directory is not defined!\n");
}
}