Byte alignment Problems

Source: Internet
Author: User

For ia32 commands, the alignment policy used by Linux is: the address of the 2-byte data type must be a multiple of 2, while the larger data types (INT, int *, float, and double) must be a multiple of 4.

Stricter requirements for Microsoft Windows alignment -------- the address of any k-byte basic object must be a multiple of K, K = 2, 4, or 8.

In fact, after extending to the X86-64 directive, it's all the last alignment.

Here, we need to point out that the basic object of K bytes is considered, that is, we only consider the basic data type.

Consider the following struct:

Struct P1 {int I; char C; long J; char D ;};

The offset of I is 0, and the required alignment is 4.

The offset of C is 4, and the required alignment is 1.

The offset of J is 8, and the required alignment is 8. (Not 5, because it does not meet the alignment policy)

The offset of D is 16, and the required alignment is 1.

The entire struct occupies 24 bytes. It can be analyzed. Originally, 17 bytes are acceptable. However, considering the alignment requirements of each basic data, the size of the entire struct must be a multiple of 8. And

The alignment of the entire struct must be 8. (Only basic data types are considered. Therefore, alignment by 8 can meet the alignment requirements ).

 

The second struct:

Struct P2 {short w [3]; char * C [3];} (64-bit program, so the pointer is 8 bytes)

The offset of W is 0, and the required alignment is 2. (Again, only basic types are considered)

The offset of C is 8, and the required alignment is 8.

Therefore, the entire struct occupies 32 bytes and requires an alignment of 8.

 

The third struct:

Struct P3 {struct P1 a [2]; struct P2 * P ;};

The offset of A is 0, and the required alignment is 8.

The offset of P is 48, and the required alignment is 8.

Therefore, the entire struct occupies 56 bytes and requires an alignment of 8.

Byte alignment Problems

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.