Topic: Alignment requirements


Author: fjh@munta.cs.mu.OZ.AU (Fergus Henderson)
Date: 1995/09/02
Raw View
bkline@cortex.nlm.nih.gov (Bob Kline) writes:

>I have found (on more than one occasion) published code which
>appears to rely on an assumption about c++ for which I haven't
>been able to find any justification in the ARM or the draft
>standard itself.  The assumption is that a static array of
>char is guaranteed to be suitably aligned to hold objects of
>any types overlaid on the array's space.

Such code is neither strictly conforming nor portable.

>So my question is: does the draft standard require that all arrays
>of char be placed by the compiler at an address which would meet
>the alignment requirements for any object which might be placed
>there?

No, it does not.  Nor is the final version of the C++ standard likely to.

There is currently NO strictly conforming way of doing this, although
there is a portable way.  The portable way is as follows.  First,
define a type MaxAlign that has maximal alignment.  (This is the part
that can be done portably, but not strictly conformingly.)  Second,
instead of using just a plain static array of characters, use an
anonymous union with MaxAlign:

 union {
  MaxAlign dummy_union_member_to_force_alignment;
  char bigBuf[4096];
 };

To define the type MaxAlign, use a union of all the types that might
possibly have difficult alignment requirements:

 /* A type with the maximum alignment requirents */
 typedef union {
   long i;  /* integer */
   void *p;  /* pointer */
   double d1;  /* floating point */
   long double d2;
   void (*f)(void); /* function pointer */
 } MaxAlign;

The problem is that there is no standard-conforming way of guaranteeing
that MaxAlign really does have the maximum alignment requirement.

It has been suggested (by myself, and also others) that a `MaxAlign'
(or `max_align_t', as it would probably be called if it were
in the implementation's namespace) type should be added to the standard
library, to allow a standard-conforming way to write code like the
example in Coplien that you quoted.  This is currently still on one of
the committee's "open issues" lists.

--
Fergus Henderson             |  #define x t=a[i],a[i]=a[m],a[m]=t
                             |  char a[]=" 12345678";main(m,i,j,t){for(i=m;i<
fjh@cs.mu.oz.au              |  9;x,i++)for(x,j=m;--j?(t=a[m-j]-a[m])-j&&t+j:
http://www.cs.mu.oz.au/~fjh  |  main(m+1)*0;);m-9||puts(a+1);} /* 8 queens */

[ comp.std.c++ is moderated.  Submission address: std-c++@ncar.ucar.edu.
  Contact address: std-c++-request@ncar.ucar.edu.  The moderation policy
  is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]