3
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.

1
  • One small problem I do see with the code in your link is that strcmp and strncmp returns the result differently. strcmp unnecessarily clamps the result to the -1..+1 range, while strncmp returns the full difference. Commented Dec 21, 2010 at 9:20

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

s1 is implicitly guarded due to zero-termination. The zero-termination will lead to there being a difference between "*(unsigned char ) s1" and "(unsigned char *) s2", terminating the loop.

So no, the code looks correct to me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.