The analysis of sizeof function in C + +--solving the problem of sizeof seeking structure size

Source: Internet
Author: User

The amount of memory that is consumed by different data types in C/

All-in-one

Char 1 1

int 4 Most 4, a few 8

Short 2 2

Long 4 8

Float 4 4

Double 8 8

Pointer 4 8

(Units are bytes)

struct (struct): More complex, alignment problem.

Union (Union): The longest of all members.

Enumeration (enum): Depending on the data type.

sizeof calculates the size of a single-layer structure

The operator sizeof can calculate the size of a given type, and for a 32-bit system , sizeof (char) = 1; sizeof (int) = 4. The size of the base data type is very good, let's look at how to calculate the size of the constructed data type.

There are three types of construction data in C: arrays, structs, and common bodies.

An array is a collection of elements of the same type, as long as the size of a single element is calculated, and the entire array occupies space equal to the number of elements on the base element multiplied by the element.

Members in a struct can be of different data types, and members are stored sequentially in contiguous memory space in the order in which they are defined. Unlike arrays, the size of a struct is not a simple addition to the size of all members, and it is necessary to take into account the problem of address alignment when the system is storing structural variables . Let's look at a struct like this:

 struct   stu1 { int   I;        char   C;   int   J; };  

      uses sizeof to find the size of the structure, the value is 12. int is 4 bytes, char accounts for 1 bytes, and the result should be 9 bytes.

First, we introduce a related concept- offset . Offset refers to the difference between the address of a member in a struct variable and the address of a struct variable . Structure Size equals the last member's offset plus the size of the last member . Obviously, the address of the first member of a struct variable is the first address of a struct variable. Therefore, the first member I has an offset of 0. The offset of the second member, C, is the offset of the first member plus the size of the first member (0+4), its value is 4, the offset of the third member J is the offset of the second member plus the size of the second member (4+1), with a value of 5.

However, in practice, when storing variables, the address requires alignment , and the compiler follows two principles when compiling the program:

(1) The offset of a member in a struct variable must be an integer multiple of the member size (0 is considered to be an integral multiple of any number)

(2) The size of the struct must be an integer multiple of all member sizes, or common multiple of all member sizes.

The first two members of the above example have offsets that meet the requirements, but the third member has an offset of 5, not an integer multiple of its own (int) size. When processing, the compiler will fill 3 empty bytes after the second member, making the offset of the third member 8. The size of the struct is equal to the last member's offset plus its size, the above example calculates a size of 12, which satisfies the requirement.

Let's look at another example:

struct STU2  {        int  k;          Short t;  } ;  

The offset of member K is 0, and the member T has an offset of 4, which does not need to be adjusted. But the calculated size is 6, which is obviously not an integer multiple of the member K size. Therefore, the compiler will make up 2 bytes after the member T, making the size of the struct 8 to meet the second requirement.

Therefore, the structure type needs to take into account the case of byte alignment, the different order will affect the size of the structure .

Compare the following two kinds of definition order:

struct STU3  {          char  C1;           int i;          Char C2;  }   struct Stu4  {         char  C1;          Char C2;          int i;   }  

Although the members of the struct STU3 and Stu4 are the same, sizeof (struct STU3) has a value of 8 and sizeof (struct STU4).

sizeof calculates the size of nested structures

For nested structures , you need to expand them . In the case of sizeof, these two principles become:

(1) The offset of the first member of the expanded struct should be an integer multiple of the largest member in the expanded struct.

(2) struct size must be an integer multiple of all member sizes, where all members calculate the expanded member instead of the nested struct as a whole .

Look at the following example:

struct Stu5  {        short  i;         struct          {             char  C;              int J;        } SS;          int k;  }  

The offset of the member ss.c of the struct STU5 should be 4, not 2. The entire structure size should be 16.

The following code tests Principle 2:

 struct   Stu5 { char   I;  struct   { char   C;         int   J;         } SS;         char   A;         char   b;         char   D;         char   E;   char   F; }  

The struct SS calculates a separate footprint of 8, while Stu5 sizeof is 20, not an integer multiple of 8, which means that when sizeof (STU5) is calculated, the nested struct SS is expanded so that the largest member of STU5 is SS.J, takes 4 bytes, and 20 is an integer multiple of 4. If you consider SS as a whole, the result should be.

Another special example is that the struct contains an array whose sizeof should be expanded as if it were a nested struct, as in the following example:

struct SS  {      float  F;       Char p;       int adf[3];  };  

  its value is. Float takes 4 bytes, the offset to char P is 4,p to one byte, the offset to int adf[3] is 5, expands to an integer multiple of int, not an integer multiple of int adf[3], so that the offset is 8 instead of 12. The result is 8+12=20, which is an integer multiple of the size of the largest member float or int.

How to allocate space for struct variables is determined by the compiler, which is for GCC under Linux. The VC platform under Windows is also like this, as for other platforms, there may be different processing.

Thanks: Thank you for your patience and reading!

The analysis of sizeof function in C + +--solving the problem of sizeof seeking structure size

Related Article

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.