Yes, behavior of your code is undefined. However, as long as you are using if (memcmp(str1, str2, 3) == 0)
(note that byte count is 3 instead of 4. I.e. minimum of two), behavior of your code would be acceptable and correct.
The behavior is undefined if access occurs beyond the end of either object pointed to by lhs and rhs. The behavior is undefined if either lhs or rhs is a null pointer.
In case of strcmp, it stops as soon as if finds \0
. However, for memcmp,
it is flawed assumption, that memcmp compares byte-by-byte and does not look at bytes beyond the first point of difference. The memcmp function makes no such guarantee. It is permitted to read all the bytes from both buffers before reporting the result of the comparison.
So, I would write my code like this:
#include <stdio.h>
#include <string.h>
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
int main()
{
char str1[] = "abcd";
char str2[] = "ab";
int charsToCompare = MIN(strlen(str1), strlen(str2)) + 1;
if (memcmp(str1, str2, charsToCompare) == 0)
{
printf("equal string\n");
}
return 0;
}
More details and analysis on memcmp
can be found here.