http://gcc.gnu.org/bugzilla/show_bug.cgi?id=36566

--- Comment #6 from Gabriel M. Beddingfield <gabriel at teuton dot org> ---
All assignments of obj.s to type short& and short* are incorrect, and ideally
they would all result in compiler errors.

The C++ spec (C++03, Sects. 3.9, 3.9.1, 3.9.2) are very clear that T and
"pointer to T" have implementation-specific alignment requirements.  If you
have a "pointer to T" then you may assume that it meets the alignment
requirements.  I'm sure the C spec has similar language.

In the OP's case, the following code could violate the alignment requirements:

    short& pit(obj.s); /* invalid */

For example &obj.s could have an address 0x602011 (which has 1-byte
alignement).  When you assign that pointer to pit... pit is now a reference
(i.e. pointer) that violates the alignment requirements of short (which usually
requires 2-byte alignment).

Why is this a problem?  On x86/x86_64 it's *usually* no big deal because the
CPU will gracefully handle unaligned memory access (with a performance
penalty).  On less forgiving hardware platforms, trying to use `pit' will
result in illegal instruction exceptions.

You can pass the reference if you change the function prototype to something
like:

    typedef short un_short __attribute__((alignment(1)));
    void VerticallyChallenged(un_short&) {}

...and then call it with a cast like this:

    VerticallyChallenged((un_short&)oj.s);

[amazing, the kind of stuff you learn over the course of 4 years :-)]

Reply via email to