Structure Alignment

M

Mike C#

Hi all,

I was having a discussion with a co-worker about alignment of structures in
memory, and we came across a question. We have a struct like the following:

struct Car
{
unsigned char VIN[17];
unsigned char Make[26];
unsigned char Model[26];
unsigned short Year;
...
}

The sizeof(struct) is 916 bytes. If we want to compile and run this code on
64-bit Windows do we need to add a 4-byte array to the struct to make it
align on an 8-byte boundary? Or will the compiler handle that for us?
Also, are there any other reasons we might want to 'force' it to line up on
an 8-byte boundary? For instance, if we want to call the function from
other languages, etc.?

Thanks
 
B

Bruno van Dooren

I was having a discussion with a co-worker about alignment of structures
in memory, and we came across a question. We have a struct like the
following:

struct Car
{
unsigned char VIN[17];
unsigned char Make[26];
unsigned char Model[26];
unsigned short Year;
...
}

The sizeof(struct) is 916 bytes. If we want to compile and run this code
on 64-bit Windows do we need to add a 4-byte array to the struct to make
it align on an 8-byte boundary?

No.
see here:
http://msdn2.microsoft.com/en-us/library/83ythb65.aspx
Or will the compiler handle that for us?
yes

Also, are there any other reasons we might want to 'force' it to line up
on an 8-byte boundary? For instance, if we want to call the function from
other languages, etc.?

You should not have to do this yourself unless you want to reserve fields
for future use and want to maintain binary compatibility.

What you might need to do is to explicitly set pack size for specific
structures.
One reason to do this would be if your dll is used in an environment where a
specific pack size is expected.
For example, I know that the LabVIEW language uses pack size 1 for
structures, instead of the default 8.

see this for more details:
http://msdn2.microsoft.com/en-us/library/2e70t5y1.aspx

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
M

Mike C#

Cool, thanks! I don't think we have a specific pack size here (I haven't
been through all the code for all these applications yet though), but I just
want to make sure we don't have to do any clunky stuff to prevent problems
as we start porting some of this stuff to 64-bit machines. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top