Structure Padding and Binary Files

Structure Padding

Consider the following code and result.

int has a size of 4 
char has a size of 1
double has a size of 8
Assumed struct 'Student' size = 62
Actual struct 'Student' size = 64

Padding Concept,align%20the%20data%20in%20memory

  • It reads 1 word at a time.
  • The processor does not read 1 byte at a time.
  • The 32-bit processor → reads 4 bytes at a time → 1 word = 4 bytes →
    Hence, accessing 4 bytes at a time
  • The 64-bit processor → reads 8 bytes at a time → 1 word = 8 bytes
    Hence, accessing 8 bytes at a time
struct A {   
char x;
char y;
int z;
Reference from: padding is a concept,align the data in memory


There are ways to avoid structure padding in C. One way is to use __attribute__((packed)) and the other way is to use #pragma. We can turn on and off of using a pragma before a declaration of a class or structure and after the declaration of the structure respectively. The following code and result show a way to let my above program not use structure padding. Now, both the human calculated answer has the same size of structure Student.

age has a size of 4 
1 block of name has a size of 1
weight has a size of 8
Assumed struct 'student' size = 62
Actual struct 'Student' size = 62

Reading and Writing Binary Files

First and foremost, binary files do not have any newline characters. We have to use ios::binary to prevent C++ from messing around. Let us used what we learned in pragma and modify the example class to see the use of pragma can make a difference. Consider the following code.


I have illustrated how the structure padding is automatically used by default C pre-processor, as well as the reason why is there such a setting. Meanwhile, I have also mentioned how to use pragma to avoid padding in a struct, as well as the general possible reason why to use a pragma when we write binary files, ensuring blocks of memory sending to the receiver is in the standard.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Cheung

Kevin Cheung

𝑾𝒉𝒂𝒕 𝑰 𝒄𝒂𝒏𝒏𝒐𝒕 𝒄𝒓𝒆𝒂𝒕𝒆, 𝑰 𝒅𝒐 𝒏𝒐𝒕 𝒖𝒏𝒅𝒆𝒓𝒔𝒕𝒂𝒏𝒅. . An ordinary developer records his life and learning progress.