The C getenv() function reads an environment variable. It searches the host environment for an exact name and returns access to its current value. Environment contents and case rules are platform-dependent.
This function is declared in <stdlib.h>. Its contract matters as much as its call: validate every required precondition, check any documented sentinel, and keep ownership or host effects clear in the surrounding code. Success returns a pointer to the variable's value, which may be an empty string. Failure to find the name returns NULL; that differs from a present-but-empty value. The examples below move from the direct call to an edge condition and a practical use.
Syntax
Start with this concrete getenv() call:
C
getenv("PATH");
Call
What it does
getenv("PATH");
Reads an environment variable using the concrete values shown.
Include <stdlib.h>. Also include headers that declare any types, limits, locale tools, or I/O functions used around the call.
Library declaration
C
char *getenv(const char *name);
Parameters
Parameter
Description
name
Null-terminated environment-variable name.
Return Value
Return Value
Description
Pointer to string
The variable exists; the pointed text is owned by the environment.
NULL
No matching variable exists.
C Examples
Example 1 — Read a common variable
This complete program demonstrates a distinct part of the getenv() contract and checks the result or precondition that matters for the scenario.
C
#include <stdio.h>
#include <stdlib.h>
int main(void){const char *value=getenv("PATH");printf("PATH present: %s\n",value?"yes":"no");}
Output
PATH present: yes
(on typical systems)
How It Works
Step 1. Pass the exact variable name.
Step 2. Store the borrowed pointer as read-only text.
Step 3. Check for NULL before using it.
Step 4. Report presence without assuming a particular path value.
Example 2 — Distinguish missing from empty
This complete program demonstrates a distinct part of the getenv() contract and checks the result or precondition that matters for the scenario.
Step 2. Measure enough space including the null terminator.
Step 3. Copy into checked caller-owned storage.
Step 4. Free the independent copy after use.
Frequently Asked Questions
getenv() reads an environment variable. It searches the host environment for an exact name and returns access to its current value. Environment contents and case rules are platform-dependent.
Include <stdlib.h> before calling getenv().
Success returns a pointer to the variable's value, which may be an empty string. Failure to find the name returns NULL; that differs from a present-but-empty value.
Do not free or modify the returned string. A later environment-changing operation may invalidate it; copy the text if it must be retained.
The function is specified by the C standard library. Exact limits, locale behavior, environment behavior, allocation capacity, or host effects can still vary where relevant.