0

I'm new to C and am attempting to accept a string from stdin and pass it as a void pointer to a struct (this is a requirement for the program) and then covert it back to a string again in order to print it to stdout.

I tried to print the string from inside a function (the struct was passed as a parameter to the function), but it kept printing out garbage, so I added a print statement in the main method itself to see if it would print garbage there too, and it is.

Here is the struct:

struct Params
{
    int key;
    void *value;
};

here's part of the main function:

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

    else if (map.f_values == 's') 
        {
            int key; // key will always be an int
            printf("Enter a key: ");
            fflush(stdin);
            scanf("%d", &key);

            char* value;
            printf("Enter a value: ");
            fflush(stdin);
            scanf("%s", value);

            printf("we got: %s\n", value); //prints correctly

            struct Params call2Params = {key, value};
            
            printf("the length of the string is %ld", strlen(call2Params.value));
            printf("sending: %d, %s\n", call2Params.key, (char*)call2Params.value); //value prints garbage
        }
}

Strange thing is, this works perfectly fine on my mac, but it prints garbage when I run it on a linux VM.

Please let me know if you know what's going on and how to fix it!

  • `char* value;` That's an unintialised pointer. It can contain any garbage address/value. Writing to such is Undefined Behaviour. You need to point it to a valid buffer (`malloc` some memory). – kaylum Apr 28 '22 at 01:22
  • And kindly burn whatever madness of a reference, site, or curricula is telling you to use `fflush(stdin)` . [It invokes *undefined behavior*](https://stackoverflow.com/questions/2979209/using-fflushstdin). `fflush` is only intended on *write* streams. – WhozCraig Apr 28 '22 at 01:41

0 Answers0