Nono
Nono

Reputation: 1103

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.

Upvotes: 0

Views: 2656

Answers (3)

mah
mah

Reputation: 39807

When you defined char *input; you satisfy the compiler because your syntax is valid: when calling scanf("%s", input); you are saying you want a string and it should get placed wherever input is.

The problem is input isn't anywhere (initialized) yet... where it points is undefined at the moment; before using any pointer you must make it point somewhere that is valid (and large enough to hold whatever you intend to put there).

There are a few ways you can solve this, but perhaps the easiest is to decide how large the input needs to be and declare a character array, such as: char input[512];. Be aware that this is problematic because if the input exceeds your buffer you will overwrite other memory... but this should get you moving forward for now.

Upvotes: 2

Alexander Kemp
Alexander Kemp

Reputation: 202

char is a single char.
char *input declares a variable which hold a pointer to a character, but there is no memory for the data. In C, this is a correct behavior. However, sscanf expects that you actually pass a pointer which points to allocated memory (please consider that the function does not return any pointer, so it has no chance of allocating memory for you).

So between declaration and use, please use malloc to allocate memory.

Upvotes: 1

P.P
P.P

Reputation: 121387

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.

Upvotes: 4

Related Questions