Explain getenv() Function in C with Example

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.

If you wish to look at all C Tutorials, go to C Tutorials.

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!
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter