Un-alignment in structures

John Bruner jdb at mordor.UUCP
Tue Mar 26 04:05:06 AEST 1985


One of the objections that has been raised against unaligned structures
in C is that you can run into trouble if you create a pointer to an
unaligned element and pass that pointer to a function.  If the machine
can't access unaligned data (e.g. an odd address on a PDP-11) the
program will die when it tries to reference through the pointer.  Worse,
if the structure items are not aligned on byte boundaries such a pointer
might not even make sense.

The solution to this problem is to disallow the unary '&' operator
from operating upon elements of a packed/unaligned structure.  This
is the solution in Pascal, which does not permit a component of a
packed record to be passed by reference (as a "var" parameter).  There
is at least a weak precedent for this in C with the "register" storage
class.

I'm involved with software development for a machine with a (gack)
36-bit word, and C's inability to define bitfields which cross longword
boundaries (and the VAX PCC's inability to deal with integers wider than
32 bits) makes life miserable.  By contrast, our other system development
language, Pastel (a "colorful" Pascal), makes things much less painful.
All our object files must be created with 9 8-bit bytes containing the
data for 8 9-bit bytes.  In Pastel the conversion is all done by
the compiler.  In C I had to write routines which explicitly
mask and shift to get the desired effect.  The problem is much worse
if you consider that assemblers, linkers, etc. often want to look at
one group of bits at a time (e.g. the opcode field is the upper 12
bits).  In Pastel I can declare a packed array of packed records (each
record is a 36-bit word), index into the array, and extract the desired
element.  In C I have to read a block of bytes, convert them into
some internal format (e.g. 12 bits per 16-bit "short") and then mask
and shift some more if the field I want crosses a 12-bit boundary.

No feature is free, of course, and bit-aligned structure elements
do increase the complexity of the compiler.  However, if they aren't
used they do not increase the size or runtime of the resulting
program.  (Although the Pastel compiler takes more time and space at
compile time than PCC, the resulting programs are usually faster and
smaller.  PCC wins only when the program is very pointer-intensive.)

I suppose that I could do what I want using C++, but although LLNL
is operated by the University of California we aren't really an
educational institution.  Hence, I can't get it.
-- 
  John Bruner (S-1 Project, Lawrence Livermore National Laboratory)
  MILNET: jdb at mordor.ARPA [jdb at s1-c]	(415) 422-0758
  UUCP: ...!ucbvax!dual!mordor!jdb 	...!decvax!decwrl!mordor!jdb



More information about the Comp.lang.c mailing list