On Nov 26, 2012, at 3:57 PM, Bill Beech (NJ7P) wrote:

> I have run into a problem with both 4.6.1 and 4.7.2 of the gcc compiler 
> handling type short.  Sizeof(unsigned short) returns a length of 2 as 
> expected, but when I use a union of a character buffer and some fields 
> including a unsigned short the value returned is 2 bytes but the buffer 
> pointer is moved 4 bytes.
> ...
> As you can see the value at 0410 in the file, 6601 is returned as 358, which 
> is correct.  The 4-byte
> value following 67 01 00 00 is not returned for the unsigned int but rather 
> 00 00 30 00 is returned next (which equals 3145728 decimal).  While a 
> sizeof(unsigned short) returns 2 bytes, in this case the pointer into the 
> unioned buffer is moved 4 bytes.
> 
> This bug makes it hell to you any of your products to build emulators for the 
> 16-bit processors.
> 
> Is there a definition for a 16-bit quantity that will work in a union?
> 
> Thanks!
> 
> Bill Beech
> NJ7P

You meant struct, right, not union?

Every field has a size as well as an alignment.  The starting address of each 
field is forced to be a multiple of its alignment.  In many cases, for 
primitive data types (like the various size integers) the alignment equals the 
size; for example, a 4-byte int has alignment 4.

So if you have a struct of short then int, the compiler has to insert 2 bytes 
of padding before the int to obey the alignment.

In some cases, there are types that don't have alignment == sizeof, for example 
long long int on Intel is size 8 but (by default) alignment 4.

Since you mentioned 16-bit processors -- are you talking about a port for a 
16-bit processor, where you want int (size 4) to be aligned 2?  (For example, 
that would be sensible on a PDP-11.)  If so, you'd want to tell the compiler 
how to do that; I'm not sure of the details, presumably they are in the GCC 
Internals manual.

Or are you talking about an existing port which has defined the alignment of 
int to be 4?  If so, that might be because unaligned accesses would cause 
exceptions.  Or it may just be a convention.  In either case, you can use the 
"packed" attribute to override the normal alignment of fields.  See the GCC 
documentation for details.

        paul

Reply via email to