Two Problems of C ++ byte alignment that are easy to be ignored

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.