Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Memory Alignment & Structure Padding

Lesson 40 of 53 in the free Foundation of C & C++ notes on Siksha Sarovar, written by Rohit Jangra.

The Hidden Bytes in your Structs

Have you ever checked the sizeof your structure and found that the numbers don't add up?

struct Data {
    char a; // 1 byte
    int b;  // 4 bytes
};
// You might expect 5, but sizeof(Data) is usually 8!

Why does this happen?

CPUs are optimized to read data from memory addresses that are "aligned" (multiples of 4 or 8). Reading an integer from address 1003 is much slower than reading it from address 1000. To keep the CPU happy, the C compiler adds invisible padding bytes between your variables to ensure they land on "good" addresses.

How to Save Memory

You can often shrink your structures by simply ordering your variables from largest to smallest.

  • Bad: char, int, char, int (Lots of padding).
  • Good: int, int, char, char (Minimal padding).

#pragma pack(1)

If you are sending data over a network or writing to a file format, you might want to disable padding entirely. This directive tells the compiler: "Do not add any padding, pack these bytes as tightly as possible."

Use the sizeof operator frequently during development to verify that your structures aren't ballooning in size due to hidden padding!