C-language struct variable memory allocation and address alignment

Source: Internet
Author: User

Address alignment is simply to improve the speed of accessing memory.

The address assignment of an array is simple, and because of the same data type, address alignment is a natural thing.

Because of the combination of different basic data types, there are different cases of address alignment, but generally there are the following rules:

Principle 1: Data member Alignment rules: A data member of a struct, where the first data member is placed at an offset (offset) of 0, where the starting position of each data member store will start from an integer multiple of that member size (for example, an int is 4 bytes in a 32-bit machine, then it is stored from an integer multiple address of 4).

Principle 2: The final work: the total size of the structure, that is, the results of sizeof, must be the largest member of its internal integer times, insufficient to complete.

Principle 3: struct as a member: if there are some struct members in a struct, the struct member is stored from the integer multiple address of its internal maximum element size. (struct A contains elements such as char,int,double in a struct b,b, and that B should be stored in multiples of 8.) )

Like what

struct Type1 {int A; double b;}

if: Int occupies 4 bytes, double is 8 bytes;

1. Analyze the Alignment rules:

The int offset is 0, and if the starting position of the direct deposit double,double after int is 4, it does not conform to the alignment rule, so the double start position is 8.

2. Analysis of closure rules:

int accounts for 4 bytes, 4 bytes, and double for 8 bytes. Altogether 16 bytes, which is an integer multiple of the internal maximum member (8). So sizeof (type1) = 16;

C-language struct variable memory allocation and address 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.