Search code examples
cpointerscharacterc-stringsstrcmp

Weird bug in custom strcmp (C)


I had a task of writing custom strcmp that will compare two strings kinda ignoring the spaces in them (meaning, " a b c" is "abc") and return some positive number if str1>str2, negative if str2>str1 and 0 if str1=str2. Here is the code

int mystrcmp(const char *str1, const char *str2)
{
    while (*str1 != '\0' && *str2 != '\0') {
        while ((*str1) == ' ') {
            str1++;
        }
        while ((*str2) == ' ') {
            str2++;
        }
        if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
            return (unsigned char) *str1 - (unsigned char) *str2;
        }
        str1++;
        str2++;
    }
    return (unsigned char) *str1 - (unsigned char) *str2;
}

The problem is that it doesn't work properly with "ab " and "ab", which are considered equal. Those whiles should get both str1 and str2 pointers to '\0', then subtract them and return 0. Instead, it returns 32, meaning it doesn't get str1 to '\0'. What am I missing?


Solution

  • Your loop stops whenever a '\0' is found in one of your string. But the other string might still contains space. When you compare "ab"
    and "ab ", the second string will never be fully iterated other. You need to make sure that both your strings do not end up on a space. Try this fix:

    while (*str1 != '\0' && *str2 != '\0') {
        while ((*str1) == ' ') {
            str1++;
        }
        while ((*str2) == ' ') {
            str2++;
        }
        if (*str1 != *str2 || *str1 == 0 || *str2 == 0)
             break ;
        str1++;
        str2++;
    }
    while (*str1 == ' ')
        str1++;
    while (*str2 == ' ')
        str2++;
    return (unsigned char) *str1 - (unsigned char) *str2;