getenv() Function in C

Question: What is getenv() Function and What this Function does in a C Program?

Answer: An ‘Environment’ is an implementation-defined list of NAME/VALUE pairs maintained by the O.S.. Standard defines specific meanings to “Environment Variables”. Not all implementations necessarily define same set of Environment Variables but they must define same meanings to whatever Environment Variables they have. ‘getenv()’ function is declared in ‘stdlib.h’ header and prototyped as below

    char *getenv(char const *NAME);

This function searches for NAME environment variable in the list and returns its value. Notice here that program must not modify value of NAME variable. Let’s write a C program and attempt to access several environment variables, for example,

/* getenv.c -- program accesses environment variables */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int main(void)
    char *str;
    /* attempt to access environment variables using getenv() */
    assert((str = getenv("HOME")) != NULL);
    printf("Value of \"HOME Environmemt Variable\" : %s\n", str);
    assert((str = getenv("PATH")) != NULL);
    printf("Value of \"PATH Environmemt Variable\" : %s\n", str);
    assert((str = getenv("LOGNAME")) != NULL);
    printf("Value of \"LOGNAME Environmemt Variable\" : %s\n", str);
    /* attempt to access variable of ours' choice */
    assert((str = getenv("MELLO")) != NULL);
    printf("Value of \"MELLO Environmemt Variable\" : %s\n", str);
    return 0;

Observe the output below

Value of "HOME Environmemt Variable" : /root
Value of "PATH Environmemt Variable" : /usr/lib64/ccache:/usr/local/sbin:
Value of "LOGNAME Environmemt Variable" : root
a.out: getenv.c:20: main: Assertion `(str = getenv("MELLO")) != 
((void *)0)' failed.
Aborted (core dumped)

Notice that ‘getenv()’ takes ‘NAME environment variable’, searches this in the list and when found returns its value as a string. When it fails, it returns NULL pointer.

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.