Home > Software engineering >  Why does getenv returns NULL here?
Why does getenv returns NULL here?

Time:01-08

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv, char **envp) {
    for (int i = 0; envp[i] != NULL; i  ) {
        printf("%d.%s\n", i , envp[i]);
    }

    char *aux;

    if (getenv(envp[0]) != NULL) {
        aux = getenv(envp[0]);
    } else {
        printf("NULL\n");
    }

    return 0;
}

I want to print a specific value of an enviorment variable but getenv returns null and i dont know why.When i say getenv("USER") for example it works fine

CodePudding user response:

The call to getenv(envp[0]) returns NULL because you are passing a string that contains the key and its value. Just pass the key.

For example, envp[0] in my system is

ALLUSERSPROFILE=C:\ProgramData

not

ALLUSERSPROFILE

CodePudding user response:

From the man page:

The getenv() function searches the environment list to find the environment variable name, and returns a pointer to the corresponding value string.

"Re: isnt the value: /bin/bash?"

You answered your own question. getenv searches for a variable name, and returns it's value. But you passed it envp[0], which contains both the name and it's value, hence the NULL.

"SHELL" is a valid argument to getenv, while SHELL=/bin/bash is not.

  •  Tags:  
  • c
  • Related