Simple analysis of two problems of C + + byte alignment easily ignored _c language

Source: Internet
Author: User
Share two of issues that have been overlooked in development here:
1, Union (Commonwealth) byte alignment
First look at the code:
#pragma packs (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 environment, the answer is 20.
By debugging the memory layout of the structure, it is found 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];
};
The union then becomes 16 bytes, plus 2 char-type bytes, which, in order to maintain struct's own byte alignment, populates two bytes at the end of the struct.
The memory layout of the final structure is like this:
#pragma packs (4)
struct COM
{
Union
{
Double dtest;
int ntest;
Char sztest[14];
BYTE padding1[2];
};
Char ChTest1;
Char ChTest2;
BYTE padding2[2];
};
#pragma pack ()

2, different compiler environment default byte alignment difference
Do platform transplant colleagues should pay attention to, encountered an indeterminate byte alignment problem, it is best to try first, not too take for granted:
(1) Under Win32, the VC compiler defaults to 8-byte alignment, and supports 1, 2, 4, 8, 165 alignment methods.
(2) Linux 32, GCC 4.1 default 4-byte alignment, support 1, 2, 43 alignment. So the structural body
Even if you encounter a 8-byte variable such as double, long long, it is still aligned in 4 bytes. Even if the #pragma pack is set (8)
(3) Android 4.0, ARM CPU NDK compilation environment, by default, when you encounter a double, long type variable, unlike PC Linux 32, it 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.