How big is sizeof structure?

  sonic0002        2012-10-29 12:13:37       3,895        0    

First let's see the codes of a structure:

struct node{
    int a;
    int b;
};

Question : What's sizeof(node)? The answer is very simple, on a 32 bit machine, an int will take 4 bytes and two ints will take 8 bytes. So sizeof(node) is 8.

The answer for the above codes is 8, then how about the following structure:

struct node{
    char a;
    int b;
};

Question : Then what's sizeof(node) now? int takes 4 bytes, char takes 1 bytes, is the answer 5?

Now the answer may not be 5, on some machines, the answer is 8. Why?

In fact, this is not the problem of the language. You will not find why in ANSI C. Even you are in different systems, different compilers, you may get different results. Then who does change 5 to 8?

This introduces a concept called data structure alignment. Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

In fact, for the efficiency, compiler will put some padding bits on the adjacent variables. x86 is 4 bytes aligned, so sizeof(node) is 8 , not 5.

One more example:

struct node{
    int a;
    char b;
    char c;
    int d;
    char e;
};

Then what's sizeof(node) now? It's 16.

Then if we know alignment is done by compilers, then can we modify the padding bits? The answer is yes, in C, we can use

#pragma pack(n)

to change the padding bits

Note : The above codes are compiled in x86 Linux with gcc compilers, on other systems the compiler may get different results.

Let's see one more example:

        struct node {
                double a;
                int b;
                int c;
                char d;
        };

Then what's sizeof(node) now? 20? 24?

You will find if you compile it with VC on Windows, you will get 24, if you compile with gcc compiler on Linux, you will get 20. This indeed explains that the data structure alignment is not determined by compilers.

Source : http://www.spongeliu.com/218.html

DATA STRUCTURE ALIGNMENT  PACK 

       

  RELATED


  0 COMMENT


No comment for this article.



  RANDOM FUN

Vim exists everywhere