Sunday, June 19, 2016

Memory Padding

Memory Padding
Lets understand Memory padding by an example.

#include <iostream>
using std::cout;
struct checkSize
{
    int a;
    char b;
    short int c;
    int d;
    char e;
};
int main()
{
  cout <<"Size of structure::"<<sizeof(checkSize);
  return 0;
}
Given Condition:: System is 32 bit. Size of int = 4 bytes, char = 1 byte and short int = 2 bytes.
As we expect the output of this as 12 bytes. But the actual answer is 16 bytes.
Reason:; Memory Padding is used in this.
In a 32 bit system, the bus have limit carry only 32 bits or 4 bytes of data in one time. Or in other word we can say system bus carry data in a group of 4 bytes. Through memory padding technique system tries to group the data in size of 4 bytes in this case also.
int a; 4 byte           -- group 1
char b; 1 byte        -- group 2
short int c; 2 byte  -- group 2
int d; 4 byte           -- group 3
char e;  1 byte       -- group 4
The memory is grouped in the sequence of initialization of the variable.
Group 1 and 3 will contain 4 bytes while group 2 contains 3 bytes and group 4 contains only 1 byte.
If we would have initialized like below, if would have took only 12 bytes of memory.
struct checkSize
{
    char e;
    char b;
    short int c;
    int d;
    int a;
};
Memory padding technique is not used in Class in C++.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


No comments:

Post a Comment