what is structure padding ?
if the system is 32 bit system,
we are allocating memory like this:
struct test
{
char a;
int b;
};
It will allocate 8 bytes of memory in 32 bit system. For char,compiler
will allocate the 4 bytes. [char may be 1 or 2 bytes]
this is called data alignment. 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.
For char, 4 bytes are allocated. it will use only 1 bytes.Rest of the
bytes are filled with junk values. this is called structure padding.
For example, in 32 bit system,the data to be read should be at a
memory offset which is some multiple of 4.
if the data starts from the 18th byte, computer has to read two 4
bytes chunks to read the data.
if the data starts from multiple of 4[4,8,12,16,20], computer can read
4 byte chunk once to read the data.
If the read is from two virtual memory pages, then it will take more
time than expected.
In this way, padding improves performance.
if the data members are declared in descending order it will give
minimal wastage of bytes.
struct Test
{
char a;
int b;
char c;
};
sizeof(Test) is 12 bytes.
But if we declared like this, 8 bytes will be allocated for structure "Test".
struct Test
{
int b;
char c;
char a;
};
How to avoid structure paddding?
if we dont want to waste memory & tradeoff the performance,
we need to use pragma pack to align data.
0 Comments:
Post a Comment
<< Home