Some Questions about Data Alignment in C/C ++

Source: Internet
Author: User

When I first came into contact with the concept of "Data Alignment", I was probably learning the basic structure of C language. At that time, I remember the teacher saying that this is the most common question for job interviews in the future. Later, although I understood the basic idea, I did not go into the details about the specific reasons in the computer system, probably in exchange for space efficiency. When I browsed the blog Park last night, I noticed that a friend wrote this article. When I read it, I always felt that the explanation was quite awkward, which is quite different from my previous understanding. Because I did not perform more verification when I accessed the Internet through a mobile phone, I suddenly remembered this problem when I turned on my computer. I simply wrote a test program to verify it. We also reviewed the concept of data alignment.

I found a lot of Chinese documents and explained the reasons for Data Alignment as follows:

1. Platform reason (transplantation reason): Not all hardware platforms can access any data on any address; some hardware platforms
The platform can only retrieve certain types of data at certain addresses; otherwise, a hardware exception is thrown.
2. Performance reasons: Data Structures (especially stacks) should be aligned on natural boundaries as much as possible. The reason is that
For non-alignment memory, the processor needs to access the memory twice, while for alignment memory, only one access is required.

First, let's look at the first example:

  1. # Include <iostream>
  2. Using namespace STD;
  3. Struct S1 {
  4. Char K;
  5. Double I;
  6. Char C;
  7. };
  8. Int main (INT argc, char ** argv)
  9. {
  10. Cout <sizeof (struct S1) <Endl;
  11. Return 0;
  12. }

This example is taken from "blog Garden". The output result of the above explanation is 24, while the output result of GCC compilation on Redhat x86 is 16, comply with the two Data Alignment rules I previously remembered:1. The default value is 4 bytes. 2. If all members are smaller than the default value, the maximum value of all members is used.However, I think it is correct to take a closer look at the blog garden's explanation. The above explanation is probably like this:

If the values of each field are stored consecutively, the double type I may be allocated in two 8-byte memory blocks, and two memory accesses may be performed, the current memory is allocated to K, I, and C all occupy 8 bytes, so that the double type I value can be obtained after one access to the memory. K is followed by 7 bytes, that is to say, the offset of I is 8, and 7 bytes of C are also wasted, even though it does not have any fields. This is obviously a waste of memory.

What I can think of is that alignment is different on different machines. I have also sorted out some materials for reference at the end of the article ..

Let's look at another program as follows:

  1. # Include <iostream>
  2. Using namespace STD;
  3. Typedef struct {
  4. Char C1;
  5. Long L;
  6. Char C2;
  7. Double D;
  8. };
  9. Typedef struct {
  10. Char C1;
  11. Char C2;
  12. Long L;
  13. Double D;
  14. } B;
  15. Int main (INT argc, char ** argv)
  16. {
  17. Cout <"sizeof (A) =" <sizeof (a) <Endl;
  18. Cout <"sizeof (B) =" <sizeof (B) <Endl;
  19. Return 0;
  20. }

This program should be run in Windows XP and compiled and executed using VC ++ 6.0. The execution result of the above program is

However, the GCC compilation and execution results for the same program in Linux are as follows:

The above two programs are analyzed as follows:

1. When using VC ++ 6.0 for compiling in Windows XP, C1 occupies one byte for the char type, and then needs to be filled with three bytes for the natural alignment of L. L is long type, occupies 4 bytes, C2 IS char type, in order to make the double precision D alignment, you need to add 7 bytes in C2, then D occupies 8 bytes. The result is: 1 + 3 + 4 + 1 + 7 + 8 = 24. According to the same rules, the space occupied by struct B is 16.

2. in Linux, when GCC is used for compiling, it is supplemented by four bytes. That is to say, the four elements in structure a occupy 4, 4, 4, 8, and 20 in total, among them, 20 is a factor of 4, which meets the Data Alignment principle in Linux.

It seems that such an exception is related to the platform and compiler.

The above alignment method is called natural alignment. When learning the C compilation tool, remember to set the Pragma to force alignment. For example, the above program is changed to the following:

  1. # Include <iostream>
  2. Using namespace STD;
  3. # Pragma pack (2)
  4. Typedef struct {
  5. Char C1;
  6. Long L;
  7. Char C2;
  8. Double D;
  9. };
  10. Typedef struct {
  11. Char C1;
  12. Char C2;
  13. Long L;
  14. Double D;
  15. } B;
  16. # Pragma pack ()
  17. Int main (INT argc, char ** argv)
  18. {
  19. Cout <"sizeof (A) =" <sizeof (a) <Endl;
  20. Cout <"sizeof (B) =" <sizeof (B) <Endl;
  21. Return 0;
  22. }

The running result is:

Analysis: Since the alignment is set to 2 bytes through # pragma, the space occupied by the four elements in struct a is 2, 4, 2, 8, and 16. The total size of struct B is similar.

To sum up, there are two scenarios for # pragma pack (n) Forced alignment:

  • First, if n is greater than or equal to the number of bytes occupied by the member, the offset must meet the default alignment, that is, the natural alignment.
  • 2. If n is less than the number of bytes occupied by the member type, the offset is a multiple of N, and the default alignment mode is not required. 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.

Some Questions about Data Alignment are summarized here. The original Article address is: Baidu blog and some training institution materials. The summary is not very complete, mainly to explain some of my personal understanding, there are many cases of Data Alignment, which are not listed here. The following lists the reference URLs and some PDF documents for download:

    • Http://www.cnblogs.com/hlxs/archive/2012/10/03/2711128.html
    • Http://www.cnblogs.com/hardcandy/archive/2011/08/08/2131377.html
    • Http://home.51.com/fogball/diary/item/10055783.html
    • Data Alignment
    • Data Alignment details

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.