Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp() thinks that strings arent equal.. but are they? [duplicate]

For unknown reason, result of running my C program is quite unexpected. I think that it has to be some kind of a beginner mistake, however I can't find out really, where is it.

#include <stdio.h>
#include <string.h>
int main()
{
char string1[50];
char string2[50];
int compare;

puts("Enter two strings: ");
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);

compare=strcmp(string1, string2); /* usage of extra variable makes the code more readable but wastes more memory */

printf("%d: ",compare);

if (compare<0) puts("First string is lesser");
else if (compare>0) puts ("First string is bigger");
     else puts("Strings are equal");


return 0;
  }

And on testing:

Enter two strings: 
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger


------------------
(program exited with code: 0)
Press return to continue

Shouldn't those strings be equal?

like image 668
hardpenguin Avatar asked Aug 24 '12 11:08

hardpenguin


2 Answers

fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);

These are wrong. string1 and string2 are not initialized, and strlen just counts the number of bytes, till hitting \0. In this case, strlen could return any (random non-negative) number.

Use sizeof, instead of strlen here.

like image 177
Kiril Kirov Avatar answered Oct 05 '22 12:10

Kiril Kirov


Here

 char string1[50]; 
 char string2[50]; 

you dont initialise them, so your initial calls to strlen are unreliable as they are looking for the first null char they find after the start of the array. This could be anywhere and the results of the call may or may not be a true reflection on the size - you just cant rely at all on the results.

like image 23
mathematician1975 Avatar answered Oct 05 '22 12:10

mathematician1975