1

We know that the correct order of declaring variables in structures changes the size of a structure also because of padding. I have seen the reference here.

Suppose a structure is:

struct s {
    char b; //1 for char
    char c; //1 for char + 2 for padding
    int a; //4 for int
}my_struct;

So the size of the my_struct is 8, but without padding it could be 6 which is less than 8.

So my question is: Why padding is done in structures? What is the necessity of this concept?

Because without padding the structure is of lesser size. My question is not related to when padding take place, it is more concerned about the concept of padding.

Community
  • 1
  • 1
Subinoy
  • 478
  • 7
  • 22
  • 2
    Read: [Alignment](http://en.wikipedia.org/wiki/Data_structure_alignment) – P.P Jun 02 '15 at 06:48
  • 1
    http://en.wikipedia.org/wiki/Data_structure_alignment#Hardware_significance_of_alignment_requirements – Colin Basnett Jun 02 '15 at 06:49
  • This solved my issue: http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member – Subinoy Jun 02 '15 at 06:54
  • Sorry for duplicate question but I searched a lot but couldn't find the answer properly – Subinoy Jun 02 '15 at 06:55
  • To answer your question in a word its performance. The best long answer I have found so far is this write up from none other than Eric S Raymond: [The Lost Art of C Structure Packing][1] [1]: http://www.catb.org/esr/structure-packing/ – yasouser Jun 02 '15 at 06:56

1 Answers1

1

Many computer architectures have optimized memory access in an alignment different than 1 byte (usually, 1 word = 4 bytes). Aligned accesses is generally faster than unaligned ones (and sometimes, it is impossible to access unaligned data). For this reason, compilers pack the struct members in an optimally aligned fashion. In your example, it looks like the alignment is of size 2 bytes, thus b is at offset 0, c is at offset 2 and a is at offset 4, totaling 8 bytes (assuming a is 4 bytes long). Or, according to the inline comments, in your example, it looks like the optimal alignment is equal to the data size. Thus, b and c are adjacent because the size is 1 and so is the alignment, but a is 4 bytes long, and hence needs a 4-byte alignment.

At the bottom line - this is all very architecture dependent.

ysap
  • 7,723
  • 7
  • 59
  • 122