I wrote a small code piece of code in C to test strncmp()
, memcmp()
functions. Here is the code.
#include <stdio.h>
#include <string.h>
int main()
{
const char s1[] = "abcd\0\0\0\0";
const char s2[] = "abcd\0abc";
printf("strncmp(s1, s2, 4) = %d\n", strncmp(s1, s2, 5)); //0
printf("strncmp(s1, s2, 8) = %d\n", strncmp(s1, s2, 8)); // why returns 0? Thx
printf("memcmp(s1, s2, 4) = %d\n", memcmp(s1, s2, 5)); // 0
printf("memcmp(s1, s2, 8) = %d\n", memcmp(s1, s2, 8)); // -120
return 0;
}
I found strncmp(s1, s2, 8) = 0
while memcmp(s1, s2, 8) = -97
. Because \0
is not equal to a
, I think strncmp(s1, s2, 8)
should return a non-zero value.
Then I tried to print s1
and s2
lengths, both of them are 9. And I tried to test more cases, strncmp()
works as expected.
Finally, I tried a similar case as s1
and s2
, strncmp
returns a fault value. The following is my code:
#include <stdio.h>
#include <string.h>
int main()
{
const char s1[] = "abcd\0\0\0\0";
const char s2[] = "abcd\0xyz";
printf("strncmp(s1, s2, 4) = %d\n", strncmp(s1, s2, 5)); //0
printf("strncmp(s1, s2, 8) = %d\n", strncmp(s1, s2, 8)); // why returns 0? Thx
printf("memcmp(s1, s2, 4) = %d\n", memcmp(s1, s2, 5)); // 0
printf("memcmp(s1, s2, 8) = %d\n", memcmp(s1, s2, 8)); // -120
printf("sizeof(s1) = %lu\n", sizeof(s1)); // 9
printf("sizeof(s2) = %lu\n", sizeof(s2)); // 9
printf("%d\n", strncmp("\0", "a", 1)); // -1
printf("%d\n", strncmp("\0\0", "ab", 2)); // -1
printf("%d\n", strncmp("a\0", "ab", 2)); // -1
printf("%d\n", strncmp("a\0\0", "a\0b", 3)); // 0, why?
return 0;
}
I guess maybe strncmp()
will not compare characters after it meets \0
? Isn't that how strcmp
works. I'm not sure that strncmp()
works like strcmp()
.