Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two string literals using memcmp

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?

like image 338
msc Avatar asked May 02 '18 07:05

msc


People also ask

How do you compare string literals?

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.

How does memcmp work in C?

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.

How do you compare two strings are similar?

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.

Can we compare two strings directly?

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.


1 Answers

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

like image 50
Bathsheba Avatar answered Oct 14 '22 02:10

Bathsheba