Avocado
Avocado

Reputation: 97

Characters from two different arrays match despite them being different

I have defined a function that should, when called and given two strings, check whether letters of the first string exist in the second one. This is my code :

int lettersOfAInB(char a[], char b[])
{
    int count = 0;

    for(int i = 0; a[i] !='\0'; i++)
    {
        count = 0;
        for(int j = 0; b[j] !='\0'; j++)
        {
            if(a[i] == b[j])
            {
                count = 1;
                break;
            }
        }
        if(count == 0)
            return 0;
    }
    return 1;
}

int main() 
{
    char a[5] = "zc";
    char b[4] = "oabq";
    int is;

    is = lettersOfAInB(a, b);

    if(is)
        printf("Yes");

    printf("\n");
    return 0;
}

This will always output "Yes", regardless of the strings I give as parameters. Could someone explain me why please? Thank you.

Upvotes: 2

Views: 69

Answers (1)

chux
chux

Reputation: 153498

Could someone explain me why please?

Undefined behavior (UB)

for(int j = 0; b[j] !='\0'; j++) attempts to access char b[4] beyond its 4 elements. Result UB. Anything may happen.


If code it to treat char b[] as a string (an array with a null character), allows the compiler to make the array size as needed

// char b[4] = "oabq";
char b[] = "oabq";  // now `b[]` has 5 ellements

Upvotes: 1

Related Questions