开发者

C \ UNIX \ strcmp first use is wrong, correct all other times

开发者 https://www.devze.com 2023-02-22 02:28 出处:网络
hey all i wrote some code on microsoft VS which is suppose to compare passwords entered to ones stored in database and return approved or denied...

hey all i wrote some code on microsoft VS which is suppose to compare passwords entered to ones stored in database and return approved or denied... it worked perfectly good on windows, but after converting to UNIX (using eclipse) a funny thing happend - always, the first call to this function doesnt return the approved value when it should, but calling for the function again with exactly the same params returns approved... as desired. after debugging i am pretty sure the problem is in the "strcmp", that returns false on the first run and true in all other runs on the exact same parameters.

anyone has an idea on what could be the problem??

an example for a commands: add jt 111 // adding the password to the DB

login jt 111

denied

login jt 111

approved

void login_helper(char *user, char *pass开发者_如何学编程word){
        int found = 0;
        int i;
        for (i=0 ; i<space ; i++){
            if (strcasecmp(data[i].name,user) == 0) {
                found = 1;
                if (strcmp(data[i].hash ,Md5FromString(password)) == 0)
                    {
                    printf("approved.\n");
                    break;
                }
                else {
                    printf("denied.\n");
                    break;
                }
            }
        }
        if (found == 0) printf("denied.\n");
    }


I predict that the call to Md5FromString(password) returns a pointer to a buffer that's no longer valid when the Md5FromString() function returns. That would mean that you're running into undefined behavior, and getting lucky in some cases and unlucky in others.

Post the code to Md5FromString().


I'd really doubt there's any problem in strcmp(). :-)

(There's an excellent book on SW development called "The Pragmatic Programmer", by Andrew Hunt and David Thomas, which has a tip regarding debugging called "'select' is not broken", which ultimately means that it's really unlikely that a basic system function (e.g. select() or strcmp()) is broken.)

Did you try printf'ing the contents of 'data[i].hash' and the value returned by 'Md5FromString(password)' right before strcmp()?

Something like:

            char *md5;
            ...
            md5 = Md5FromString(password);
            printf("i: %d, hash: %s, md5: %s\n", i, data[i].hash, md5);
            if (strcmp(data[i].hash, md5) == 0)
                {
                ...

Also, who allocates memory for function Md5FromString()? Can you send the code for Md5FromString()?

Cheers, Paulo

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号