Useful macro...or dangerous??

Pablo Halpern pablo at polygen.uucp
Fri Apr 29 11:04:18 AEST 1988


>From article <221 at raunvis.UUCP>, by kjartan at raunvis.UUCP (Kjartan Pier Emilsson Jardedlisfraedi):
[ Introduces attempt at macro for testing structure equality ] 
> #define EQ(A,B) equal(A,B,sizeof(*(A)))
> 
[ Gives example of use ]
> 
> equal(a,b,size)
> char *a,*b;
> long int size;
> {
> while(*(a+si-1)== *(b+si-1) && si>0)
> 	si--;
> if(si==0)
> 	return(1);
> else
> 	return(0);
> }
> 
> I herewith submit my possible blunders to the Blowtorches of the Net.
> 
> 		Kjartan Pierre Emilsson, Reykjavik, ICELAND

With one correction, your method MIGHT be useful but not certainly fool
proof.  First the correction: according to K&R, the sizeof operator
returns an int.  According to dpANS, the sizeof operator returns
size_t.  No document that I know of defines sizeof as returning long
int, so equal() should be redefined as follows (I also did code optimization):

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 would work ONLY IF THERE ARE NO HOLES IN THE STRUCTURES BEING COMPARED.
For example, the following would not work on many architectures.

	struct {
		char	c;
		int	i;
	} x, y;
	...
	if (EQ(&x, &y))
		...;

On many machines, x.i and y.i will be aligned on word boundaries (i.e.,
they must have addresses that are multiples of the word size, typically
2, 4, or 8).  That means that there could be a gap or "hole" of several
bytes between the end of x.c and the beginning of x.i.  There is no
rule about what values fill this hole; they could be different for x
and y.  Thus, your byte for byte comparison could fail on these holes
even if the structures matched field by field.  Your method would
only work for some structures on some architectures and would be very
non-portable.  Sorry to burst your bubble.

Pablo Halpern		|	mit-eddie \
Polygen Corp.		|	princeton  \ !polygen!pablo  (UUCP)
200 Fifth Ave.		|	bu-cs      /
Waltham, MA 02254	|	stellar   /



More information about the Comp.lang.c mailing list