Search code examples
cenvironment-variablesscanfgetenv

C - scanf() and then getenv()


I'm asking the user which environment variable he want to know and then I scan it with scanf. But it doesnt work for me. Here is my code:

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


    int main(int argc, char *argv[]){

        char *value;
        char input;

        printf("Which variable do you want?\n");
        scanf("%s", input);

        value = getenv(input);

        printf("%s", value);

    }

The compiler says:

"Function argument assignment between types "const char*" and "char" ist not allowed"

So i tried to change the input variable to: char const *input

Now there is no compiler error, but when I submit a name, for example "USER", I get a "Segmentation fault (core dumped)" error.


Solution

  • The warning is because here

    value = getenv(input);
    

    you pass a char to getenv(), which has the prototype:

       char *getenv(const char *name);
    

    Define input as a char array like:

        char input[256];
    
        printf("Which variable do you want?\n");
        scanf("%255s", input); //specify the width to avoid buffer overflow
    

    Or, you can use dynamically memory allocation (using malloc) if you think 256 is not big enough for your purposes.