Today, I will share with you two problems that are easily overlooked in C ++ byte alignment. The following questions are also encountered in my actual development work. If you have different opinions, please contact us.
Here we will share two issues that have been ignored during development:
1. byte alignment of Union
First look at the Code:
# Pragma pack (4)
Struct com
{
Union
{
Double dTest;
Int nTest;
Char szTest [14];
};
Char chTest1;
Char chTest2;
};
# Pragma pack ()
Sizeof (struct com) =?
In the gcc 4.1 and vc 2005 environments, the answer is 20.
After debugging the memory layout of the structure, we found that the union itself was added with two bytes to maintain the 4-byte alignment of the Union itself.
That is, the union becomes in the memory:
Union
{
Double dTest;
Int nTest;
Char szTest [14];
Byte Padding1 [2];
};
In this way, union is changed to 16 bytes. After adding two char-type bytes, in order to keep the struct's own byte alignment, it is added to the end of struct.
The memory layout of the final struct is as follows:
# Pragma pack (4)
Struct com
{
Union
{
Double dTest;
Int nTest;
Char szTest [14];
Byte Padding1 [2];
};
Char chTest1;
Char chTest2;
Byte Padding2 [2];
};
# Pragma pack ()
2. Differences in default byte alignment in different compiler Environments
When porting the platform, you should pay attention to the problem of uncertain byte alignment. You 'd better give it a try first:
(1) In Win32, the VC compiler is 8-byte aligned by default, and supports five alignment modes: 1, 2, 4, 8, and 16.
(2) in Linux 32, GCC 4.1 is 4-byte aligned by default. Three Alignment modes are supported: 1, 2, and 4. Therefore, struct
Even if an 8-Byte variable such as double or long is encountered, it is still 4-byte aligned. Even if # pragma pack (8) is set)
(3) Android 4.0 and arm cpu NDK compiling environment. By default, variables of the double and long types are different from those of PC Linux 32, alignment is 8 bytes aligned.