Memory allocation of structures

Charles Hannum CMH117 at psuvm.psu.edu
Tue Mar 6 08:01:24 AEST 1990


In article <1457 at navy8.UUCP>, kreidler at cell.mot.COM (Joe Kreidler) says:
>
>  ...
>
>Is there some reason for structures being allocated memory as I described
>above? Is this observation part of the ANSI standard? Any insights are
>appreciated.


Yes, there are two very good reasons for this.  Consider the following:

struct {
    short a,
          b,
          c;
}   foo;
typedef struct {
    int   d;                          short  8-bit
    short e;                          int   16-bit
}   bar;
bar foobar[] = {{0,1},{2,3},{3,4},{4,5}};


There are several problems with this:

1)  bar must be word-aligned!  Try accessing a 16-bit integer on an odd
    boundary on a PDP-11 (or an 80x86, where it takes twice as long as if
    the int was at an even address)!   Okay, so maybe the *beginning* of
    a struct should be word-aligned.  This brings us to ...

2)  What if I want to use (sizeof(foobar)/sizeof(bar)) to determine the
    number of elements in bar?  Here's what I'd get:

         (3+1+3+1+3+1+3)/3 = 15/3 = 5

    (The 1s represent the word-alignment of the elements in foobar.)
    This obviously not correct.

The only solution to this problem is to make the *end* of the structure
word-aligned, in which case neither of these problems occur.


Virtually,
- Charles Martin Hannum II       "Klein bottle for sale ... inquire within."
    (That's Charles to you!)     "To life immortal!"
  cmh117 at psuvm.{bitnet,psu.edu}  "No noozzzz izzz netzzzsnoozzzzz..."
  c9h at psuecl.{bitnet,psu.edu}    "Mem'ry, all alone in the moonlight ..."



More information about the Comp.lang.c mailing list