C source code strcmp

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 am looking at the code: http://www.jbox.dk/sanos/source/lib/string.c.html

I suppose there is some kind of problem. If strlen(s2)>strlen(s1), then it ++s1may be out of range. Unfortunately, then the function returns an error.

+3
source share
3 answers

No, there is no such problem, because the cycle continues only when * s1 and * s2 are equal, and * s2 is not 0. If s1 is shorter, then when it gets to \ 0 at the end of s1, the equality condition will be interrupted, and the cycle will stop .

+7
source

No, there is no such problem provided that s2 '\ 0'-is completed.

+1
source

s1 - . "* (unsigned char) s1" "(unsigned char *) s2", .

, .

+1

Source: https://habr.com/ru/post/1781404/


All Articles