Play and learn 300 000+ tabs online

Thursday, June 3, 2010

Structure padding - Memory alignment

Padding a structure with unnamed members in order to maintain a proper
alignment is

called structure padding.


It can be explained with a simple example...... (Under UNIX machine)



struct X

{

char ch;

int i;

char a ;

char b;

long l;

};


How the structure is padded is explained below.....

First the compiler allots a 4-byte location to the char variable ch.
Since ch occupies only

one byte the remaining 3 bytes are left unused. Now the compiler checks
whether the

next variable i.e (int i) can be inserted in the unused space. Since int
occupies 4 bytes

it can't be inserted in the available space of 3 bytes.. So what the
compiler does is it

pads the 3 unused bytes with some unknown names....


Now the memory of 4 bytes will be allocated to int i. After
this, the compiler assigns a 4-byte location to char a. Since char
occupies only one byte 3 bytes are left

unused. Now the compiler checks whether the next variable can be
inserted in the left over space. Since the next variable is a char ,
which can be fit in the left over space.

Thus a 2-byte location is padded... Hope the concept is clear.....

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.