Two issues that C + + byte alignment is easy to ignore

Source: Internet
Author: User
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.

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.