[comp.lang.c] forcing struct allignment

les@chinet.chi.il.us (Leslie Mikesell) (07/21/89)

I have a program that current writes a variety of different structs
into a disk file and maintains the seek offsets to access them as needed.
Is there a way to pad them such that the allignment would be correct
if the whole file were read into a malloc()ed block of memory or would
I still have to memcpy() each struct into a correctly alligned memory
block before accessing the members?  When each struct is written to the
disk, the program does not know the type of the struct that will follow.

Les Mikesell

njk@freja.diku.dk (Niels J|rgen Kruse) (07/22/89)

les@chinet.chi.il.us (Leslie Mikesell) writes:

>I have a program that current writes a variety of different structs
>into a disk file and maintains the seek offsets to access them as needed.
>Is there a way to pad them such that the allignment would be correct
>if the whole file were read into a malloc()ed block of memory or would
>I still have to memcpy() each struct into a correctly alligned memory
>block before accessing the members?  When each struct is written to the
>disk, the program does not know the type of the struct that will follow.

My suggestion is:

  Let (d1,d2, .. ,dn) be the struct tags of the structs, that
  you want to handle.

  Define a union (lets call it maxalign) of all the leaf non-composite
  member types of any of the structs.

  For each of (d1,d2, .. ,dn) define a union (du1,du2, .. ,dun)
  as
        union du1 {
          struct d1 d;
          union maxalign m;
        }

  Then `sizeof (union du1) - sizeof (struct d1)' is the minimum amount
  of padding required after a struct d1, such that any struct can
  follow it. Of course, if any of the structs are smaller than
  the maxalign union, there may be some waste, but that is unavoidable
  unless you are willing to tweak the maxalign union for each machine.

Of course, wait a while to see if this is torn apart by the language gurus.
-- 
         Niels J|rgen Kruse
Email    njk@diku.dk
Mail     Tustrupvej 7, 2 tv, 2720 Vanlose, Denmark