Is the way static data alligned correct?

Bernd Walter ticso at cicely12.cicely.de
Sun Mar 14 23:32:35 PST 2004


On Mon, Mar 15, 2004 at 04:01:45PM +0900, Alexander Nedotsukov wrote:
> Guys,
> 
> Recently doing some development I hit alignment problem on alpha 
> machines. Problem solved but the way I did it in fact the reason why I 
> asking pros to judge who is wrong here.
> Inside code I have linked-in data blocks generated by external tool. 
> They looks like this:
>    const unsigned char raw_data_block[] = { bla-bla-bla };
> Internal block content is 8 bytes aligned. Each block resides in a 
> single .c file. So after compilation I have a set of .o files linked 
> later into single shared object (library). Taking an address of such 
> data block and casting it to pointer to some real structure was a 
> problem because it is not necesary 8 byte aligned. Obvious solution was 
> to ask explicitly for such alignment:
>    const unsigned char raw_data_block[] __attribute__ ((alligned(8))) = 
> { bla-bla-bla };
> But I wonder is this gcc bug or space optimization for char arrays only?

You request an array of bytes and you get the natural alignment of
bytes - why should the compiler waste bytes that are not required for
the variable you define?

A portable way would be to define it as a union with an int64_t.

But the real point is that you shouldn't access any variable with
stricter alignment than they are.
If you have const data as in your example then define it as the
correct structure.
If it's not constant data then bcopy it into your structure or
directly read it in a malloc'ed buffer.

-- 
B.Walter                   BWCT                http://www.bwct.de
ticso at bwct.de                                  info at bwct.de



More information about the freebsd-alpha mailing list