Search code examples
cmemorystructmemory-alignment

Data Alignment for C struct


There is a problem (3.45) in CS:APP about the byte offsets of all fields in the following struct.

struct {
  int    *a;
  float  b;
  char   c;
  short  d;
  long   e;
  double f;
  int    g;
  char   *h;
} rec;

Here is the answer from the book, which gives c a three bytes padding, d a two bytes padding and g a four bytes padding.

field  size  offset
-----  ----  ------
a      8     0
b      4     8
c      1     12
d      2     16
e      8     24
f      8     32
g      4     40
h      8     48

And here is my solution, which only gives c a one byte padding and g a four bytes padding.

field  size  offset
-----  ----  ------
a      8     0
b      4     8
c      1     12
d      2     14
e      8     16
f      8     24
g      4     32
h      8     40

So, what's the problem with my solution? It seems to fit the alignment rule (edit* the "rule" here is just a simplified concept summaries by myself, It's not completed or general), all object's offset is a multiple of the size of object.

Would be very thankful for any explanation.


Solution

  • The answer depends on the compiler, platform and compile options. Some examples: enter image description here

    https://godbolt.org/z/4tAzB_

    The author of the book does not understand the topic I afraid.