Help in memcmp (it may be a bug)

Hello friends today i have created a program that is working fine . but when string becomes equal it does not work .

/* String.h header series
	
	Comparison function

memcmp = return 0 if string equal  else return less or greater than value by comparing pointer first and pointer second

*/

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
/*memcmp operation*/
int i;
char str[20];
char str2[20];
printf("Enter first string: ");
fgets(str,20,stdin);
printf("Enter second string: ");
fgets(str2,20,stdin);
fflush(stdin);
i = memcmp(str,str2,20);
if(i>0){
printf("%s greater than %s\n",str,str2);
}
else if(i<0)	{
	printf("%s greater than %s\n",str2,str);
}
else {   printf("Both are eqaul\n");  }
return 0;  
}

output:

[root@apache ~]# ./mem
Enter first string: hello
Enter second string: hello
hello greater than hello

memcmp is not working if string equal and it does not return 0 on equality of string , is this a bug ?

any help

for the same input "hello"

can you try with the below code

 
i = memcmp(str,str2,5);

Consider using man strcmp ("3")

hello is 5 characters long. Not 20.

strcmp, strncmp and other similar functions are used to do string compares. A C string is terminated with a nul (ascii 0) character. This allows strcmp to determine the string's length and stop comparing. memcmp compares objects in memory. It does not check the length because it is meant to compare memory objects which often have ascii 0 characters.

You provide the length to memcmp. 20 is not the length of the word hello

To the program work the way you expect, you need to initialize the str and str2 memory areas with the same values (say, with all zeroes, for example):

(...)
char str[20];
char str2[20];

memset(str, 0, sizeof(str)); 
memset(str2, 0, sizeof(str2));
(...)

If you don�t initialize str and str2 with the same values, these areas will contain random values, so the memcmp comparison will not match, even if they both have some values in common (both begin with 'h','e','l','l','o', but you don�t know what each have after the 5 first characters, cause it is uninitialized memory).

Thanks to pflynn now it is working

i have used memset as u say it great idea first get string and fill it with 0 then compare it .

thanks pflynn

Yes Rink, but be aware that for string comparisons, strcmp - and its safe version, strncmp - are better suited, since they are specifically designed for working with strings.