简体   繁体   中英

Comparing two strings using memcmp in c

Consider the following code:

char str1[] = "Hello";
char str2[] = "Hello\0\0\0l\0o";
int x;
x=memcmp(str1,str2,sizeof(str2));
printf("%d",x);

When I run it, it shows the o/p as:

1

Can you explain the reason for this. I learned that each byte in both strings are compared and returns accordingly. But I am not clear about what happens at the end.

Your program invokes undefined behavior.

sizeof(str2) is larger than sizeof(str1) . By using that as the last argument to memcmp , you are accessing memory that you are not supposed to. That is cause for undefined behavior.

Hence, the output can be anything. It's pointless trying to make sense of it.

when you do string compare, it will stop comparing once it reaches '\\0'. In here you've done a memcmp, which will not stop until all the requested chars are read.

In this case you're comparing sizeof(str2) bytes, which in the case of str1 will give garbage after the implied '\\0' at the end.

To get a 0 on the comparison:

  • compare only sizeof(str1) or sizeof(str1)+1 bytes
  • do a string compare

Remember, it is unsafe and sometimes danger to call memcmp here because str1 has fewer length than str2.

Consider the following code:

int main()
{
    char str1[] = "Hello";
    char str2[] = "AAAAA\0\0\0l\0o";
    for(int i=0; i<sizeof(str2); i++)
        printf("%02X %02X\n", str1[i], str2[i]);
    printf("\n%X %X", (int)str1, (int)str2);
    return 0;
}

The output is

48 41
65 41
6C 41
6C 41
6F 41
00 00
41 00
41 00
41 6C
41 00
41 6F
00 00

28FEEE 28FEF4

We can see the [6]-[11] bytes of str1 is actually the first bytes of str2 , and it could be confirmed by the address of str1 and str2 . In the case, GCC/MSVC (I'm not very sure about Clang) store the two string const initalizer in a row. So when you call memcmp , after the null-terminator \\0 , the function actually compares the first byte of str2 with \\0 . But remember, the way compiler stores constant may change under any circumstance. You should not rely on this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM