Thread: Compare two char arrays is not working

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    9

    Compare two char arrays is not working

    Im trying to compare two arrays. I want to show a message "Hash is different if they are different" and "Hash is the same" if they are icual.

    Im trying like below, but Im getting always the message "hash is different" but they are the same. I dont understand why is not working because the method is comparing and when they are different it returns false, so it shoul work. Do you understand what is wrong?

    Code:
    CHAR hashaActual[] =  "4db5a10d2ea73e3f74";
    CHAR hashExpected[] = "4db5a10d2ea73e3f74
    
    
    
     BOOL test( char array1[] , char array2[] )
        {
            int i;
            for( i = 0; array1[i] && array2[i]; ++i )
            {
                if( array1[i] != array2[i] )
                {
                    return( FALSE );
                }
            }
            return( TRUE );
        }
    
    
       
    
    
      if (test(hashActual, hashExpected)){
        printf("Correct");
      }
      else{
        printf("incorrectt");
      }

  2. #2
    Old Took
    Join Date
    Nov 2016
    Location
    Londonistan
    Posts
    121
    I fixed up your example adding headers, missing semicolon, and adding a bad hash case, and this works as intended on visual studio 2015 compiled as C.
    Code:
    #include <stdio.h>
    #include <stdbool.h>
    
    
    char hashActual[]   = "4db5a10d2ea73e3f74";
    char hashExpected[] = "4db5a10d2ea73e3f74";
    char hashWrong[]    = "4db5a10d2ea73e3f76";
    
    
    
    
    
    
    bool test(char array1[], char array2[])
    {
        int i;
        for (i = 0; array1[i] && array2[i]; ++i)
        {
            if (array1[i] != array2[i])
            {
                return false;
            }
        }
        return true;
    }
    
    
    
    
    
    
    int main()
    {
        if (test(hashActual, hashExpected))
        {
            printf("Correct\n");
        }
        else 
        {
            printf("incorrect\n");
        }
        if (test (hashActual, hashWrong))
        {
            printf("Correct\n");
        }
        else
        {
            printf("incorrect\n");
        }
    
    
        return 0;
    }
    As you can see I haven't changed a thing about your test function except the return type.
    Last edited by Hobbit; 12-03-2016 at 07:57 PM.

  3. #3
    Registered User
    Join Date
    Nov 2016
    Posts
    9
    Thanks you!! It is working now. But I was trying to do this in a specific case, and in that case is not working I get always "hash is differrent", and its not different.

    The only differnce is that instead of using the hashActual array Im using hashResult array.

    Code:
     if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
        {
            DWORD i;
            CHAR hashResult[] = {};
            printf("MD5 hash of file %s is: ", filename);
            for (i = 0; i < cbHash; i++)
            {
                printf("%c%c",
                       rgbDigits[rgbHash[i] >> 4],
                       rgbDigits[rgbHash[i] & 0xf]);
                hashResult[i] = rgbDigits[rgbHash[i] >> 4];
                hashResult[i] += rgbDigits[rgbHash[i] & 0xf];
    
    
            }
    
    
            if (test(hashResult, hashExpected))
            {
                printf("hash is the same\n");
            }
            else
            {
                printf("hash is different\n");
            }
            if (test (hashResult, hashExpected))
            {
                printf("hash is the same\n");
            }
            else
            {
                printf("hash is different\n");
            }
    
    
        }

  4. #4
    Old Took
    Join Date
    Nov 2016
    Location
    Londonistan
    Posts
    121
    I admit my straight C is rusty. I am much more of a C++ guy, not having used straight C since the days of C89, but that hashresult array looks dodgy to me, it's declared with no size at all and then you proceed to access what appears to be past the end of the array. I know C99 added VLAs but I've never used them. Is that a VLA declaration?
    Perhaps you need to slim your code down to the smallest complete compilable example that exhibits the problem?

  5. #5
    Registered User
    Join Date
    Nov 2016
    Posts
    9
    This program generates a hash key from a file and its free available. Im trying to understand the program but Im also with some doubts, Im a beginner in c. I understand some parts and others not yet. And that part when I was trying to store in the hashResult array the hash I really dont understand why its not working. The issue should be there, the hash result should not be storing the correct thing, because the function to compare both arrays now its working.

    Code:
    #include <stdio.h>
    #include <windows.h>
    #include <Wincrypt.h>
    #include <stdbool.h>
    #define BUFSIZE 1024
    #define MD5LEN  16
    
    
    bool test(char array1[], char array2[])
    {
        int i;
        for (i = 0; array1[i] && array2[i]; ++i)
        {
            if (array1[i] != array2[i])
            {
                return false;
    
    
            }
        }
    
    
        return true;
    }
    
    
    
    
    DWORD main()
    {
        DWORD dwStatus = 0;
        BOOL bResult = FALSE;
        HCRYPTPROV hProv = 0;
        HCRYPTHASH hHash = 0;
        HANDLE hFile = NULL;
        BYTE rgbFile[BUFSIZE];
        DWORD cbRead = 0;
        BYTE rgbHash[MD5LEN];
        DWORD cbHash = 0;
        CHAR rgbDigits[] = "0123456789abcdef";
        PCSTR filename = "c:\\Users\\Jax\\Desktop\\files\\file.txt";
        char hashActual[]   = "4db5a10d2ea73e3f76";
        char hashExpected[] = "4db5a10d2ea73e3f76";
        char hashWrong[]    = "0a0a0a0a0a0a0a";
        hFile = CreateFile(filename,
                           GENERIC_READ,
                           FILE_SHARE_READ,
                           NULL,
                           OPEN_EXISTING,
                           FILE_FLAG_SEQUENTIAL_SCAN,
                           NULL);
    
    
        if (INVALID_HANDLE_VALUE == hFile)
        {
            dwStatus = GetLastError();
            printf("Error opening file %s\nError: %d\n", filename,
                   dwStatus);
            return dwStatus;
        }
    
    
        // Get handle to the crypto provider
        if (!CryptAcquireContext(&hProv,
                                 NULL,
                                 NULL,
                                 PROV_RSA_FULL,
                                 CRYPT_VERIFYCONTEXT))
        {
            dwStatus = GetLastError();
            printf("CryptAcquireContext failed: %d\n", dwStatus);
            CloseHandle(hFile);
            return dwStatus;
        }
    
    
        if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))
        {
            dwStatus = GetLastError();
            printf("CryptAcquireContext failed: %d\n", dwStatus);
            CloseHandle(hFile);
            CryptReleaseContext(hProv, 0);
            return dwStatus;
        }
    
    
        while (bResult = ReadFile(hFile, rgbFile, BUFSIZE,
                                  &cbRead, NULL))
        {
            if (0 == cbRead)
            {
                break;
            }
    
    
            if (!CryptHashData(hHash, rgbFile, cbRead, 0))
            {
                dwStatus = GetLastError();
                printf("CryptHashData failed: %d\n", dwStatus);
                CryptReleaseContext(hProv, 0);
                CryptDestroyHash(hHash);
                CloseHandle(hFile);
                return dwStatus;
            }
        }
    
    
        if (!bResult)
        {
            dwStatus = GetLastError();
            printf("ReadFile failed: %d\n", dwStatus);
            CryptReleaseContext(hProv, 0);
            CryptDestroyHash(hHash);
            CloseHandle(hFile);
            return dwStatus;
        }
    
    
        cbHash = MD5LEN;
    
    
        if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0))
        {
            DWORD i;
            CHAR hashResult[] = {};
            printf("MD5 hash of file %s is: ", filename);
            for (i = 0; i < cbHash; i++)
            {
                printf("%c%c",
                       rgbDigits[rgbHash[i] >> 4],
                       rgbDigits[rgbHash[i] & 0xf]);
                hashResult[i] = rgbDigits[rgbHash[i] >> 4];
                hashResult[i] += rgbDigits[rgbHash[i] & 0xf];
    
    
            }
    
    
            if (test(hashResult, hashExpected))
            {
                printf("Correct\n");
            }
            else
            {
                printf("incorrect\n");
            }
            if (test (hashActual, hashWrong))
            {
                printf("Hash is the same\n");
            }
            else
            {
                printf("Hash is different\n");
            }
    
    
        }
        else
        {
            dwStatus = GetLastError();
            printf("CryptGetHashParam failed: %d\n", dwStatus);
        }
    
    
        CryptDestroyHash(hHash);
        CryptReleaseContext(hProv, 0);
        CloseHandle(hFile);
    
    
        return dwStatus;
    }

  6. #6
    Old Took
    Join Date
    Nov 2016
    Location
    Londonistan
    Posts
    121
    As I said with that hashresult array my compiler throws an error and refuses to compile it.

    Severity Code Description Project File Line Suppression State
    Error (active) an empty initializer is invalid for an array with unspecified bound Test

    The compiler can't work out how big the array should be. If you don't specify the size it relies on the initializer list which in this case also doesn't exist.

    Code:
    char arr[10]; // create an array of 10 chars legal.
    char arr[] = "abcdefghi" // create an array of 10 chars (9 plus zero terminator) again legal.
    char arr[] = {}; // illegal. No size specified and compiler can't work out the size.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    As Hobbit has said, this is wrong
    > CHAR hashResult[]

    It needs to be something like
    CHAR hashResult[MD5LEN]
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  8. #8
    Registered User
    Join Date
    Nov 2016
    Posts
    9
    Thanks for notice that. I was trying with
    Code:
    CHAR hashResult[MD5LEN]
    and I get the same result "Hash is different", and its not. I also tried with
    Code:
    CHAR hashResult[] = "0123456789abcdef";
    but the same message "Hash is different".

  9. #9
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    This doesn't seem to make sense. Think about what it's doing. It's adding together the hex-characters from rgbDigits. E.g., '5' + 'd' = 53 + 100 = 153 which is beyond the 7-bit ascii range. Is that really what you want? Obviously this will never match your hashExpected string.
    Code:
            for (i = 0; i < cbHash; i++) {
                hashResult[i] = rgbDigits[rgbHash[i] >> 4];
                hashResult[i] += rgbDigits[rgbHash[i] & 0xf];
            }

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    At which point, you should be running the code in the debugger and setting a breakpoint on this line.
    > if (test(hashResult, hashExpected))

    Use the debugger to actually examine the data in question.
    Are you comparing (for example) the binary version with the ascii-fied version?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compare unsigned char array with const char*
    By Lazar in forum C++ Programming
    Replies: 3
    Last Post: 09-10-2015, 08:36 AM
  2. Compare Arrays
    By AmbliKai in forum C Programming
    Replies: 16
    Last Post: 11-27-2007, 11:04 AM
  3. compare strings not working
    By gtriarhos in forum C Programming
    Replies: 7
    Last Post: 09-29-2005, 12:51 PM
  4. How do I compare two arrays?
    By lime in forum C Programming
    Replies: 6
    Last Post: 07-13-2003, 09:55 PM
  5. how to compare char array with one char?
    By Jasonymk in forum C++ Programming
    Replies: 6
    Last Post: 03-28-2003, 09:49 AM

Tags for this Thread