This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Is ISO memcmp("abc","ade",10000) safe?
- From: Jakub Jelinek <jakub at redhat dot com>
- To: Roger Sayle <roger at www dot eyesopen dot com>
- Cc: gcc-patches at gcc dot gnu dot org, gcc at gcc dot gnu dot org, Andreas Schwab <schwab at suse dot de>
- Date: Tue, 15 Apr 2003 16:51:12 +0200
- Subject: Re: Is ISO memcmp("abc","ade",10000) safe?
- References: <Pine.LNX.4.44.0304150703350.14393-100000@www.eyesopen.com>
- Reply-to: Jakub Jelinek <jakub at redhat dot com>
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