Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c strcmp source code

Tags:

c

int strcmp(const char *s1, const char *s2)

{
  int ret = 0;

  while (!(ret = *(unsigned char *) s1 - *(unsigned char *) s2) && *s2) ++s1, ++s2;

  if (ret < 0)

    ret = -1;
  else if (ret > 0)

    ret = 1 ;

  return ret;
}

I review the code from : http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose that there're some problem. If strlen(s2)>strlen(s1),then ++s1 may beyond the range. Unfortunately, then the function return error.

like image 302
lawrence rao Avatar asked Aug 12 '26 21:08

lawrence rao


2 Answers

No, there's no such problem since the loop continues only while *s1 and *s2 are equal and *s2 is not 0. If s1 is shorter, once it gets to the \0 at the end of s1, the equality condition would break and the loop would stop.

like image 130
StasM Avatar answered Aug 15 '26 15:08

StasM


No, there's not such a problem, provided that s2 is '\0'-terminated.

like image 25
Simone Avatar answered Aug 15 '26 15:08

Simone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!