The ways of bugs

Chris Torek chris at mimsy.UUCP
Fri Apr 29 21:01:41 AEST 1988


(Is this to be an entomology lesson?  Or shall we instead inquire into
the etymology of entomology?  Neither, dear reader, for these bugs have
never lived, and they care not for ... oh never mind.)

Someone `optimised' the original (buggy) `equal' (~=memcmp) function:

>int equal(a, b, size)
>char	*a, *b;
>size_t	size;
>{
>	/* byte for byte compare of structures *a and *b */
>	while (a < a + size)
>		if (*a++ != *b++)
>			return (0);
>	return (1);
>}

This is buggy.  So is another `obvious' version:

	while (--size >= 0)
		if (*a++ != *b++)
			return (0);

Since size_t is unsigned, when size is 0, --size is MAXUINT or MAXULONG
(for size_t unsigned int or unsigned long respectively).

	while (size-- != 0)

works, although it produces poor code in a number of less-than-ideal
compilers on a `conventional' condition code machine; here the loop

	if (size != 0)
		do
			if (*a++ != *b++)
				return (0);
		while (--size != 0);

tends to run faster.  On machines where only the `test' instruction
sets ccodes, the `while (size-- != 0)' may be ideal.  But (if you
have it) `memcmp' is likely to be faster still.

Remember: make it work before you make it fast, and make sure you do
not break it when you do make it fast!
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list