This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Is ISO memcmp("abc","ade",10000) safe?


On Tue, Apr 15, 2003 at 07:27:12AM -0600, Roger Sayle wrote:
> 
> I'd like to ask the C/C++ language lawyers about their interpretation
> of the definitions of memcmp given in the relevant ANSI, ISO, POSIX,
> SVID and BSD specifications.
> 
> Is memcmp("abc","ade",10000) safe by the standards?

Doesn't seem so.
ISO C99 says:
The memcmp function compares the first n characters of the object pointed to
by s1 to the first n characters of the object pointed to by s2.

So, IMHO
int
memcmp (const void *s1, const void *s2, size_t n)
{
  int ret = 0;
  int dummy = 0;

  while (n--)
    {
      if (ret == 0)
	ret = *(unsigned char *) s1++ - *(unsigned char *) s2++;
      else
	dummy += *(unsigned char *) s1++ - *(unsigned char *) s2++;
    }
  return ret ? (ret | (dummy & 1)) : 0;
}
is an conforming implementation.

	Jakub


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]