Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

getenv — C23 environment function

`getenv(name)` from `<stdlib.h>` searches the host environment list for an entry matching the null-terminated `name` string. It returns a pointer to the value string when an entry exists, or a null pointer when the name is not found.

Version: C23

Syntax

char *getenv(const char *name);

getenv(name) from <stdlib.h> searches the host environment list for an entry matching the null-terminated name string. It returns a pointer to the value string when an entry exists, or a null pointer when the name is not found.

The example queries the widely provided PATH variable and tests whether the returned pointer is non-null and the value nonempty. In the isolated execution environment it prints 1 1; the code assumes neither particular contents nor a path separator.

Do not modify the pointed-to string: the standard forbids it, and a later getenv call may overwrite it, so copy a value that must remain stable. The set of names and the method for changing the environment are implementation-defined. The function need not avoid a data race with threads that modify the environment list; synchronize such operations. Environment data is external input, so validate it before using it in paths, commands, or security configuration.

Examples

#include <stdio.h>
#include <stdlib.h>
int main(void){const char *value=getenv("PATH");printf("%d %d\n",value!=NULL,value!=NULL&&value[0]!='\0');return 0;}

Result

1 1

The example queries the widely provided `PATH` variable and tests whether the returned pointer is non-null and the value nonempty. In the isolated execution environment it prints `1 1`; the code assumes neither particular contents nor a path separator.

Sources