Useful macro...or dangerous??

Eric K. Bustad ekb at ho7cad.ATT.COM
Fri Apr 29 04:02:06 AEST 1988


In article <221 at raunvis.UUCP>, kjartan at raunvis.UUCP (Kjartan Pier Emilsson Jardedlisfraedi) asks:
> [ If the following is a foolproof way to test for structure equality. ]
> 
> #define EQ(A,B) equal(A,B,sizeof(*(A)))
> 
> 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);
> }

The main problem with this is that there are often "holes" in the
structure that should be ignored when checking for equality.  For
example, on the machine I'm on now, the structure

	struct gub {
		int a;
		char b;
	};

takes *eight* bytes of memory, four for the int, one for the char
and three more to pad it out to a multiple of eight bytes.  The
structure

	struct hvc {
		char b;
		int a;
	};

also takes eight bytes, with the extra three being inserted before
the int to place it at the proper alignment.

These holes could contain almost any kind of random garbage, so two
structures which compared equal field-wise may not when each byte is
compared in your equal() function.

= Eric



More information about the Comp.lang.c mailing list