Structure Padding

In this article we are going to see two things,

1.What is structure padding?

2.Why do we need structure padding?

Now coming to the first question,lets go through the below example.

struct Foo
{
    char a;
    char b;
    int c;
}foo;

Now normally some might thing the size of this struct is going to be 6 bytes assuming 4 bytes for int and 1 byte for each char,but if you check its going to be 8.

Lets see what exactly happens,before i start to explain lets see the below rules of memory allocation followed by the compiler when defining a structure variable.

  1. Before each individual member, there will be padding so that to make it start at an address that is divisible by its size. e.g on 64 bit system,int should start at address divisible by 4, and long by 8, short by 2.
  2. char and char[] is special, could be any memory address, so they don't need padding before them.
  3. For struct, other than the alignment need for each individual member, the size of whole struct itself will be aligned to a size divisible by size of largest individual member, by padding at end. e.g if struct's largest member is long then divisible by 8, int then by 4, short then by 2.
  4. the address in a 32 bit systems starts from (n * 8) bytes.
  5. Reason: the largest individual struct member is 8 bytes.
  6. the address in a 64 bit system starts from (n * 16) bytes.
  7. Reason: the largest individual struct member is 16 bytes
0x00 0x01  0x02 0x03
a     b     -    -

0x04 0x05 0x06 0x07
c     c    c    c

If you look at the above memory alignment,we can clearly see that 0x02 and 0x03 are left empty.This is because of the rule number 1 mentioned above.Now lets see another example

struct Foo
{
    char a;
    int c;
    char b;
    short d;
}foo;
0x00 0x01 0x02 0x03
a     -    -    -
0x04 0x05 0x06 0x07
c     c    c    c
0x08 0x09 0x10 0x11
b     -    d    d

Please note how char and short are placed in the memory inside same word in example-b. but how 2 chars are placed in example-a.

We saw how from above,lets see why now.

The architecture of CPU is such a way that it can only read 1 word at a time (4 byte for 32 bit and 8 for 64 byte) so assume that the padding is not present in a structure in the example above,to access the integer the processor must read 2 words and perform some shifting operation which would lead to more cost with respect to time.

But with padding the word containing the integer can directly be read saving time at the price of space,some times space is more important than time itself.The padding can be disabled with,

#pragma pack(n) Where: n is the alignment in bytes, valid alignment values being 1, 2, 4 and 8.




To view or add a comment, sign in

Others also viewed

Explore content categories