Padding in structures in C

letsc picture letsc · Aug 6, 2011 · Viewed 32.9k times · Source

This is an interview question. Till now, I used to think such questions were purely compiler dependent and shouldn't worry me, but now, I am rather curious about it.

Suppose you are given two structures as:

struct A {  
  int* a;  
  char b;  
 }  

and ,

struct B {  
  char a;  
  int* b;  
}  

So which one would you prefer and why? My answer went like this (though I was somewhat shooting in the dark) that the first structure should be preferred since the compiler allocates space for a structure in some multiples of the word size (which is the size of the pointer - 4 bytes on 32 bit machines and 8 bytes on 64 bit ones). So, for both the structures the compiler would allocate 8 bytes(assuming its a 32 bit machine). But, in the first case, the padding would be done after all my variables(i.e. after a and b). So even if by some chance, b gets some value that overflows and destroys my next padded bytes, but my a is still safe.

He didn't seemed much pleased and asked for one disadvantage of the first structure over the second. I didn't have much to say. :D

Please help me with the answers.

Answer

MByD picture MByD · Aug 6, 2011

I don't think there's an advantage for any of this structures. There is one(!) constant in this equation. The order of the members of the struct is guaranteed to be as declared.

So in case like the following, the second structure might have an advantage, since it probably has a smaller size, but not in your example, as they will probably have the same size:

struct {
    char a;
    int b;
    char c;
} X;

Vs.

struct {
    char a;
    char b;
    int c;
} Y;

A little more explanation regarding comments below:

All the below is not a 100%, but the common way the structs will be constructed in 32 bits system where int is 32 bits:

Struct X:

|     |     |     |     |     |     |     |     |     |     |     |     |
 char  pad    pad   pad   ---------int---------- char   pad   pad   pad   = 12 bytes

struct Y:

|     |     |     |     |     |     |     |     |
 char  char  pad   pad   ---------int----------        = 8 bytes