Search code examples
chexcommand-line-argumentsstdingnome-terminal

stdin: hex values change depending on stdin


I'm creating a hashing program that takes either a file or stdin and prints out the hash in either another file or to the terminal via stdout. My issue is I'm getting different hash values based on the same stdin because the hex values of the argument change.

the part of my code where this happens is here:

    for (i = 3; i < argc; i++) {
        if (strcmp(argv[i], "-i") == 0 && argv[i+1] != NULL) {
            in = argv[i+1];
            in = strtok(in, " ");
    printf("arg \"%s\" hex: %02x\n", argv[i+1], argv[i+1]);
            inCheck = 1;
            i++;
        }
        else if (strcmp(argv[i], "-o") == 0 && argv[i+1] != NULL) {
            out = argv[i+1];
            i++;
        }
        else 
            printf("Unknown argument %s. Ignoring.\n", argv[i]);
    }

Basically here I'm checking the hex-value of the input following "-i" in the command line. And when I enter:

./executable hash -sha -i hello -o world I get the output arg "hello" hex: ce4a2823 and when I enter:

./executable hash -sha -i hello I get the output arg "hello" hex: 247f582c and when I enter:

./executable hash -sha -o world -i hello I get the output arg "hello" hex: 57e2f82c

So I'm wondering why the hex-value of the string keeps changing?


Solution

  • You are not printing some "hex value of string", you are printing address of the string. If you want to print the hex value of the first char in the string, you can do this:

    printf("arg \"%s\" hex: %02x\n", argv[i+1], argv[i+1][0]);
    

    Hex value is possibly different, because your OS randomizes the location of the stack each time a program is run, in order to make buffer overrun/underrun bug exploits more difficult. And the argv[] strings may be stored in the stack (without checking, I think they have to be modifiable, and their length is not static of course, so putting them to the stack at program startup is a natural solution to that).


    Since you talk about "hex value of the string", a note: C string is basically just address of a piece of memory (such as a char array) containing 1 or more char: the characters of the string, and the string terminating '\0' byte (which must be there even if string is empty). It's a very primitive thing compared to string types of most other languages.