Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Padding in structures in C

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.

question from:https://stackoverflow.com/questions/6968468/padding-in-structures-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...