Top 10 structure padding questions your interviewer might ask

When you create the structure then compiler inserts some extra bytes between the members of structure for the alignment. These extra unused bytes are called padding bytes and this technique is called structure padding. structure padding increases the performance of the processor at the penalty of memory.

If you want you can avoid the structure padding using the pragma pack (#pragma pack(1) ) or attribute ( __attribute__((__packed__)) ).

You should read this article, structure padding, and memory alignment

Below table contains the alignment of some primitive data type,

Data Type32-bit (bytes)64-bit (bytes)
char11
short22
int44
float44
double88
pointer48

 

In this article, I will explain a few important questions related to the structure padding that might be asked by your interviewer. I am using dev-c++ and X64 machine.

Question 1:

Output: 12

In the above declaration, Integer is largest structure member (4 bytes) so to prevent from the penalty compiler inserts some extra padding bytes to improve the performance of the CPU. So the size of the InfoData will be 12 bytes due to the padding bytes.

 

structure padding

 

Question 2:

Output: 8

In the above example, the size of the InfoData is 8 bytes due to 2 tail padding bytes inserted by the compiler for the data alignment.

padding bytes

 

Question 3:

Output: 16

Largest structure member is double (8 bytes), hence compiler aligned the memory in the form of 8 bytes. So here compiler adds 6 padding bytes for the alignment, the size of the InfoData will be 16 bytes.

structure padding and alignment

 

Question 4:

Output: 16

Largest structure member is int (4 bytes), hence compiler aligned the memory in the form of 4 bytes.

 

Question 5:

Output: 2

Largest structure member is char (1 byte), hence compiler aligned the memory in the form of 1 byte.

Question 6:

Output: 12

Largest structure member is char (4 bytes), hence compiler aligned the memory in the form of 4 bytes.

Question 7:

Output: 24

Largest structure member is char (8 bytes), hence compiler aligned the memory in the form of 8 bytes.

Question 8:

Output: 8

Largest structure member is int (4 bytes), hence compiler aligned the memory in the form of 4bytes.

Question 9:

Output: 9

Note:  We can change the alignment of structure, union or class using the “pack” pragma directive, but sometimes it becomes a crucial reason for the compatibility issues in your program. So it’s better always use the default packing of the compiler.

Question 10:

Output: 12

Leave a Reply