I have compared two string literals using the memcmp
function.
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "abcd";
char str2[] = "ab";
if (memcmp(str1, str2, 4) == 0)
{
printf("equal string\n");
}
return 0;
}
In the above program, str2
is shorter than the str1
. It means string str2
is accessed out of bounds.
So, is this undefined behavior?
To compare string literals, still use the equality and relational operators, but for objects of the string class, and not for const char*s. Using the operators for const char*s compares the pointers, and not the string literals.
In the C Programming Language, the memcmp function returns a negative, zero, or positive integer depending on whether the first n characters of the object pointed to by s1 are less than, equal to, or greater than the first n characters of the object pointed to by s2.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
In order to compare two strings, we can use String's strcmp() function. The strcmp() function is a C library function used to compare two strings in a lexicographical manner. The function returns 0 if both the strings are equal or the same. The input string has to be a char array of C-style string.
The behaviour of your code is undefined. The C standard does not require that memcmp
returns as soon as the result is known; that is it doesn't necessarily have to return when \0
is compared with 'c'
despite the value of 'c' == '\0'
being 0
for any character encoding supported by the language. The standard also doesn't specify the order in which the lexicographical comparisons are to be made (although it would be tricky for an implementation not to start from the beginning).
str2
is a char[3]
type. It's possible that an attempt to access the 4th element is made.
Reference: http://en.cppreference.com/w/c/string/byte/memcmp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With