I'm having trouble with a key section of my code where, for some reason that is beyond my skill level at this point, it is not comparing properly. For some reason it's evaluating to true for the wrong values (O, j, r, u) and not the only right one(z). This creates an issue that cascades to the 2-4 length passwords but this is the quickest to test. Below is the code. Any help is appreciated!

int main (void) {

    //encrypted value of the char-to-string "z"     
    string pass = "50s7QGTz4Jjzc";

    //iterable version of a single char as a string
    char str_arr1[2] = {65,'\0'};

    //iterates through str_arr1 from A to z
    for (int i = 65; i <= 122; i++) 
            str_arr1[0] = i;

            //compares encrypted version of the str_arr1 and the password 
            //and print the result to the screen
            if (strcmp(crypt(str_arr1, "50"), pass) > 1) 
                printf("%s\n", str_arr1);


It looks like strcmp() isn't being used as it should. ( I don't understand why the result of strcmp is being checked for > 1. )

The strcmp(s1, s2) function compares two strings, char by char and returns one of 3 possible results. If the strings are identical, it will return 0. If the first unmatched char in s1 is smaller than the char compared in s2, then it will return a number < 0. If the s1 char is larger than the s2 char, strcmp will return a number > 0. strcmp() stops comparing after the first unmatched chars.

Note that the spec for strcmp does not specify the exact value returned when the compared chars are mismatched, other than saying they are either greater or less than 0. See the spec at https://www.tutorialspoint.com/c_standard_library/c_function_strcmp.htm

It's kind of like functions that return true or false. Functions that return false always return 0 for false. For true, they can return any non-zero (positive or negative) which will be interpreted as true. There's generally no guarantee for exactly what number will be returned (unless you can dissect the source code for the function)!

There's also the possibility that the crypt() function isn't returning what you expect.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

  • Thank you Cliff! My eyes must have been glazed over from looking at code too long when I read the strcmp manual and thought (thinking that 1 == true) that if it evaluated to anything above 0 it was true. Thanks again! – Ben May 9 '17 at 20:15
  • Don't forget, less than 0 also evaluates to true. Go figure. ;-) – Cliff B May 9 '17 at 20:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .