2012年4月14日 星期六

Alignment & Padding (English)

In order to prevent alignment exception, compiler will pad some empty data into memory to let it fit the alignment restriction.
Here is an example in C:

If we declare a structure like this:

struct align{
   char a;
   int b;
   short int c;
};

We will consider that it will use 7 bytes. However, because it has to prevent alignment exception,compiler will add some padding to let it fit 32-bit (i.e. 4 bytes). It may consider like this:

struct align{
   char a;
   char padding_0[3]; // add by compiler, programmer cannot use   
 
   int b;
   short int c;
   char padding_1[2]; // add by compiler, programmer cannot use   
};

Its memory allocation will look like this:
(放圖)

It is obvious to see that padding will waste lots of memory space. As a result, in order to save memory space, sometimes compiler also provide some pragma to let programmer to add in their code, and compiler can use these pragma to let compiler reallocate the memory allocation of this structure.

Here is an example:

#pragma pack(push)
#pragma pack(4)
        struct align
        {
                char a; //1 byte
                int b;  //4 bytes
                short int c;  //2bytes
        };
#pragma pack(pop)
It will let compiler to reallocate its memory allocation and use memory more efficiently.



Creative Commons Licence



Ref: http://en.wikipedia.org/wiki/Data_structure_alignment

沒有留言:

張貼留言