Content deleted Content added
m cleanup |
|||
Line 41:
==Typical alignment of C structs on x86==
[[Data structure]] members are stored sequentially in a memory so that in the structure below the member Data1 will always precede Data2 and Data2 will always precede Data3:
struct MyData
{
};
Line 54 ⟶ 55:
The type of each member of the structure usually has a default alignment, meaning that it will, unless otherwise requested by the programmer, be aligned on a pre-determined boundary. The following typical alignments are valid for compilers from [[Microsoft]], [[Borland]], and [[GNU]] when compiling for x86:
* A '''char''' (one byte) will be 1-byte aligned.
* A '''short''' (two bytes) will be 2-byte aligned.
* An '''int''' (four bytes) will be 4-byte aligned.
* A '''float''' (four bytes) will be 4-byte aligned.
* A '''double''' (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux.
Here is a structure with members of various types, totaling '''8 bytes''' before compilation:
Line 64 ⟶ 65:
struct MixedData
{
};
After compilation the data structure will be supplemented with padding bytes to ensure a proper alignment for each of its member:
struct MixedData
{
};
The compiled size of the structure is now '''12 bytes'''. It is important to note that the last member is padded with the number of bytes required to conform to the largest type of the structure. In this case 3 bytes are added to the last member to pad the structure to the size of a long word.
Requesting that the
While there is no standard way of defining the alignment of structure member, some compilers use ''#pragma'' directives to specify packing inside source files. Here is an example:
#pragma pack(
#pragma pack(
struct MyPackedData
{
};
#pragma pack(
This structure would have a compiled size of '''6 bytes'''. The above directives are available in compilers from [[Microsoft]], [[Borland]] and many others.
|