How to calculate the variable size

Source: Internet
Author: User
Sizeof calculates struct size (to) [Classification: Linux] published by Freeman pan at pm

Question: s output result

# Include <stdio. h>
Struct s {
Char ch, * ptr;
Union {
Short a, B;
Unsigned int c: 2, d: 1;
};
Struct s * next;
};

Int main ()
{
Printf ("% d \ n", sizeof (struct s ));
Return 1;
}

Answer: 16

1 byte ch 3bytes completion
4 bytes ptr
4 bytes union
4 bytes next
-----------------------------------------

We know that the sizeof of struct is not a simple addition of the size of the member type. I am not very familiar with the question of "". Please give a detailed answer.
Struct
{
Int;
Char B;
Double c;
};
Sizeof (A) =?

Also, what is the use of # pragma pack to set alignment?

String 9

Reprinted article:
------
1. Structure of sizeof applications

See the following structure:

Struct MyStruct

{

Double dda1;

Char dda;

Int type

};

What will happen if sizeof is used for the structure MyStruct? What is sizeof (MyStruct? You may ask:

Sizeof (MyStruct) = sizeof (double) sizeof (char) sizeof (int) = 13

However, when the above structure is tested in VC, you will find that sizeof (MyStruct) is 16. Do you know why such a result is obtained in VC?

Actually, this is a special processing of variable storage by VC. To increase the CPU storage speed, VC performs "alignment" on the starting addresses of some variables. By default, VC specifies that the offset of the starting address of each member variable to the starting address of the structure must be a multiple of the bytes occupied by the variable type. Common alignment types are listed below (vc6.0, 32-bit system ).

Type
Alignment (offset of the starting address of the variable to the starting address of the structure)

Char
The offset must be a multiple of sizeof (char), that is, 1.

Int
The offset must be a multiple of sizeof (int), that is, 4.

Float
The offset must be a multiple of sizeof (float), that is, 4.

Double
The offset must be a multiple of sizeof (double), that is, 8.

Short
The offset must be a multiple of sizeof (short), that is, 2.

When each member variable is stored, the space is requested in sequence based on the order in which the structure appears, and the positions are adjusted according to the alignment above. The vacant byte VC is automatically filled. At the same time, to ensure that the size of the structure is a multiple of the number of byte boundaries (that is, the number of bytes occupied by the Type occupying the maximum space in the structure, therefore, after applying for space for the last member variable, the vacant bytes will be automatically filled as needed.

The following uses the previous example to illustrate how VC stores the structure.

Struct MyStruct

{

Double dda1;

Char dda;

Int type

};

When allocating space for the above structure, VC allocates space for the first member dda1 according to the sequence and alignment of the member variables, the starting address is the same as the starting address of the structure (the offset 0 is just a multiple of sizeof (double). The member variable occupies eight bytes; next, allocate space for the second member dda. the offset of the next address that can be allocated to the starting address of the structure is 8, which is a multiple of sizeof (char, therefore, the dda is stored in an alignment where the offset is 8. This member variable occupies sizeof (char) = 1 byte, and then allocates space for the third member type.The offset of the next allocable address to the starting address of the structure is 9, not a multiple of sizeof (int) = 4.To meet the offset constraints of alignment, VC automatically fills three bytes (these three bytes have nothing to put ), in this case, the offset of the next allocable address to the starting address of the structure is 12, which is just a multiple of sizeof (int) = 4. Therefore, the type is stored in the location where the offset is 12, this member variable occupies sizeof (int) = 4 bytes. At this time, all member variables in the entire structure are allocated space. The total occupied space is 8 1 3 4 = 16, it is just a multiple of the number of byte boundary values of the structure (that is, the number of bytes occupied by the largest space type in the structure sizeof (double) = 8). Therefore, no vacant bytes need to be filled. Therefore, the size of the entire structure is sizeof (MyStruct) = 8 1 3 4 = 16, three of which are automatically filled by VC, without any meaningful content.

String 3

Next, let's take another example to change the position of the member variable of MyStruct above to the following:

Struct MyStruct

{

Char dda;

Double dda1;

Int type

};

How much space does this structure occupy? In the VC6.0 environment, we can obtain that sizeof (MyStruc) is 24. Based on the space allocation principles mentioned above, we will analyze how VC allocates space for the above structure. (Simple description)

Struct MyStruct

{

Char dda; // The offset is 0. The alignment is satisfied and the dda occupies 1 byte;

Double dda1; // the offset of the next available address is 1, not sizeof (double) = 8

// Multiple. You need to add 7 bytes to make the offset 8 (the alignment is satisfied ).

// Method). Therefore, VC automatically fills in 7 bytes, and dda1 is stored at an offset of 8

// Address, which occupies 8 bytes.

Int type; // the offset of the next available address is 16, which is twice that of sizeof (int) = 4.

// Number, which meets the alignment of int, so no VC auto-fill is required.

// Put the address at the offset of 16, which occupies 4 bytes.

}; // All member variables are allocated space. The total size of the space is 1 7 8 4 = 20, not a structure.

// Number of knots (that is, the number of bytes occupied by the largest space type in the structure sizeof string 2

// (Double) = 8), so four bytes need to be filled to meet the structure size

// Sizeof (double) = a multiple of 8.

Therefore, the total size of this structure is: sizeof (MyStruc) is 1 7 8 4 4 = 24. Among them, 7 4 = 11 bytes are automatically filled by VC, without any meaningful content.

The special processing of the structure storage by VC does increase the speed of the CPU storage variable, but sometimes it also brings some trouble. We also shield the default alignment of the variables, you can set the alignment of variables.

# Pragma pack (n) is provided in VC to set the variable to n-byte alignment. N-byte alignment means the offset of the Start address of the variable. First, if n is greater than or equal to the number of bytes occupied by the variable, the offset must meet the default alignment. Second, if n is smaller than the number of bytes occupied by the type of the variable, the offset is a multiple of n and does not need to meet the default alignment. The total size of the structure also has a constraint, which is divided into the following two cases: if n is greater than the number of bytes occupied by all member variable types, the total size of the structure must be a multiple of the space occupied by the largest variable;

Otherwise, it must be a multiple of n. The following is an example of its usage.

# Pragma pack (push) // save alignment status

# Pragma pack (4) // set to 4-byte alignment

Struct test

{

Char m1;

Double m4;

String 3

Int m3;

};

# Pragma pack (pop) // restore alignment

The size of the above structure is 16. Next we will analyze the storage situation. First, we will allocate space for m1, and its offset is 0, which meets our own alignment (4-byte alignment ), m1 occupies 1 byte. Then we start to allocate space for m4. At this time, the offset is 1 and three bytes need to be supplemented. In this way, the offset must be a multiple of n = 4 (because sizeof (double) is greater than n ), m4 occupies 8 bytes. When space is allocated for m3, the offset is 12, which must be a multiple of 4. m3 occupies 4 bytes. At this time, space has been allocated for all member variables. A total of 16 bytes are allocated, which is a multiple of n. If you change # pragma pack (4) to # pragma pack (16), the size of the structure is 24.

--------------

Struct about sizeof size-memory alignment

Default alignment.

In the structure, the compiler allocates space for each member of the structure based on its natural alignment condition. Each member is stored in the memory in the order they are declared, the address of the first member is the same as the address of the entire structure. By default, the C compiler allocates space for each variable or data unit based on its natural limitations.

For example, the following structure shows the allocation of member spaces.

Struct test {
Char x1;
Short x2;
Float x3;
Char x4;
};
The first member of the structure x1, whose offset address is 0, occupies 1st bytes. The second member x2 is of the short type, and its starting address must be two byte pairs. Therefore, the compiler fills a Null Byte between x2 and x1. The third member x3 and fourth member x4 of the structure exactly fall on their natural peer address, and no additional bytes are needed before them. In the test structure, the x3 member requires a 4-byte bounded boundary and is the maximum boundary unit required by all the members of the structure. Therefore, the natural boundary condition of the test structure is 4 bytes, the compiler fills in three NULL bytes after Member x4. The entire structure occupies 12 bytes of space.

The details of byte alignment are related to compiler implementation, but generally three criteria are met:
1) The first address of the struct variable can be divisible by the size of its widest basic type member;
2) The offset (offset) of each member of the struct to the first address of the struct is an integer multiple of the member size. If necessary, the compiler will add the internal adding between the members );
3) the total size of the struct is an integer multiple of the size of the widest basic type of the struct. If necessary, the compiler will add the trailing padding after the last member ).

Note:

The basic type refers to the built-in data types such as char, short, int, float, and double. The "data width" here refers to the size of its sizeof. Because the struct member can be a composite type, for example, another struct, when looking for the widest basic type member, it should include the Child Member of the composite type member, instead of seeing a composite member as a whole. However, when determining the offset of a composite member, the composite type is regarded as a whole.

Change the default Allocation Policy of the C Compiler
Generally, you can use the following method to change the default peer condition:
? Use pseudoinstructions # pragma pack ([n])
# Pragma pack ([n]) pseudoinstructions allow you to select the peer policy adopted by the compiler to allocate space for data.
For example, after the # pragma pack (1) Directive is used, the space allocation of members in the test structure is aligned by one byte. The format is as follows:
# Pragma pack (push) // save alignment status
# Pragma pack (1)
// Define your structure
//............
# Pragma pack (pop)

Appendix: number of bytes of each basic type in c

Type name            
Bytes            
Other terms            
Value Range            
Int * Signed,
Signed int
Depends on the Operating System
Unsigned int * Unsigned Depends on the Operating System
_ Int8 1 Char,
Signed char
-From 128 to 127
_ Int16 2 Short,
Short int,
Signed short int
-From 32,768 to 32,767
_ Int32 4 Signed,
Signed int
-From 2,147,483,648 to 2,147,483,647
_ Int64 8 None -From 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Char 1 Signed char -From 128 to 127
Unsigned char 1 None 0 to 255
Short 2 Short int,
Signed short int
-From 32,768 to 32,767
Unsigned short 2 Unsigned short int 0 to 65,535
Long 4 Long int,
Signed long int
-From 2,147,483,648 to 2,147,483,647
Unsigned long 4 Unsigned long int 0 to 4,294,967,295
Enum * None Same as int
Float 4 None 3.4E +/-38 (7 digits)
Double 8 None 1.7E +/-308 (15 digits)
Long double 10 None 1.2E +/-4932 (19 digits)

Basic Types of C ++:

Type bytes

  • Int 4
  • Short int 2
  • Long int 4
  • Unsigned int 4
  • Unsigned short int 2
  • Unsigned long int 4
  • Char 1
  • Unsigned char 1
  • Float 4
  • Double 8
  • Long double 8
  • Int * 4
  • Int & 4

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.