Today I would like to share with you the two problems that C + + byte alignment can easily be ignored. The following questions are also encountered in my actual development work, if there are different views welcome to the Exchange
Here to share two development issues that have been overlooked:
1, Union (Commonwealth) byte alignment
first look at code:
#pragma pack (4)
struct COM
{
union
{
double dtest
int ntest;
Char sztest[14];
char ChTest1;
char ChTest2;
};
#pragma pack ()
sizeof (struct com) =?
gcc 4.1 and VC 2005 environments, the answer is 20.
Debug the memory layout of the structure, and find that the Union itself adds 2 bytes of padding to keep the union itself in 4-byte alignment.
that union in memory becomes:
Union
{
Double dtest;
int ntest;
Char sztest[14];
Byte padding1[2];
} ;
so that the Union becomes 16 bytes, followed by 2 char-type bytes, to keep the struct's own byte aligned, and then populate two bytes at the end of the struct.
The memory layout of the final structure is as follows:
#pragma pack (4)
struct COM
{
Union
{
Double dtest;
int ntest;
C Har sztest[14];
Byte padding1[2];
};
Char ChTest1;
Char ChTest2;
Byte padding2[2];
};
#pragma pack ()
2, differences in the default byte alignment of different compiler environments
to be a platform transplant colleague to pay attention, encounterFor an indeterminate byte alignment problem, it's best to try it yourself and not take it for granted:
(1) Win32, the VC compiler defaults to 8-byte alignment, and supports 1, 2, 4, 8, 165 alignment.
(2) Linux 32, GCC 4.1 default 4-byte alignment, support 1, 2, 43 alignment. Therefore, a 8-byte variable such as double or long long in the struct body
is still aligned by 4 bytes. Even if you set the #pragma pack (8)
(3) Android 4.0, the ARM CPU's NDK compilation environment, by default, when you encounter a double, long type variable, it is different from PC Linux 32, and is aligned in 8-byte alignment.