Data Structure Alignment-Packing and Unpacking of Structures
This is a technique to manually reduce the amount of memory that a C program occupies. This method is useful for applications of C programs in low memory embedded systems. This also helps in the efficient utilization of the cache.
The term packing and unpacking seems a bit misleading. As the first instinct says the packing of a structure reduces the effective memory size of it. It may not always be right. The explanation of why it may not always be right is given below.
For example: Assuming the following struct is declared.
struct structure-name
{
char member1;
int member2;
float member3;
};
struct structure-name
Let us now see why and how a 9-byte structure is not efficient but a 12-byte structure efficient. The only data type that doesn't need memory alignment is char type as it is a single byte. This is essential because the processors access the variables memory locations based on their memory address and for both int and float types, the address locations starting number has to be divisible by 4. For an 8-byte long and double types, the starting address location has to be divisible by 8.
As one can imagine that in a system which could have more than one type of structs, and more than 1 variable initialized by these structs can cause a lot of fragmentation in the memory. The processor also needs to make more than one bus transaction to fetch the data from the structure.
This is where the concept of packing comes handy as all the structures are self-aligned helping the processor to fetch the values quicker. Packing adds more number of bits to the existing structure to make the divisibility of the starting address by 4 or by 8. This process is called padding. The bits are padded in such a way that the total number of bytes that the struct uses after padding is even.