Subject: Re: Use of sizeof()
To: Robert Black <>
From: Greg A. Woods <>
List: current-users
Date: 07/12/1995 14:32:57
[ On Tue, July 11, 1995 at 10:47:11 (+0100), Robert Black wrote: ]
> Subject: Use of sizeof()
> I have a question for anyone with intimate knowledge of the K&R C standard.
> There is some code in NetBSD (generic SCSI is one place) which makes
> assumptions about the alignment of structs. This takes the form of assuming
> that structs are only aligned to the alignment of their largest data type. For
> example with a structure like
> typedef struct
> {
> 	short a;
> 	short b;
> 	short c;
> } foo;
> it is assumed that sizeof(foo) == 6. Some compilers (notably gcc/arm) will give
> a value of 8 because all structs are word aligned regardless of contents so
> sizeof() returns the amount of space required to store a struct in an array.

If you're talking about 1978 K&R C, then I believe you can only enforce
alignment of the address of the object (but not the individual
elements), by making it a union with another object of the minimum
alignment size for the given processor. (p. 174)


#ifdef PDP11
typedef ALIGN	int;
#ifdef IBM370
typedef ALIGN	double;

typedef struct {
	union {
		short	a;
		ALIGN	x;
	} au;
	union {
		short	b;
		ALIGN	x;
	} bu;
	union {
		short	c;
		ALIGN	x;
	} cu;
} foo;

would be about the best you could do to ensure guaranteed any known
alignment of the elements of the structure.  Note though that it is
machine dependent, and the "external" representation of the structure is
not portable in either case.

Further, though it is suggested that structure elements are allocated in
the order they are declared (i.e. such that a pointer offset into the
structure is portable), this is also not explicitly stated in '78 K&R.

> Which is broken: the NetBSD code or the compiler?

The code?

							Greg A. Woods

+1 416 443-1734			VE3TCP			robohack!woods
Planix, Inc. <>; Secrets Of The Weird <>