Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does gcc calculate the required space for a structure?

Tags:

c

gcc

struct

struct {
   integer a;
   struct c b;
   ...
}

In general how does gcc calculate the required space? Is there anyone here who has ever peeked into the internals?

like image 970
R__ Avatar asked Aug 06 '11 00:08

R__


1 Answers

I have not "peeked at the internals", but it's pretty clear, and any sane compiler will do it exactly the same way. The process goes like:

  1. Begin with size 0.
  2. For each element, round size up to the next multiple of the alignment for that element, then add the size of that element.
  3. Finally, round size up to the least common multiple of the alignments of all members.

Here's an example (assume int is 4 bytes and has 4 byte alignment):

struct foo {
    char a;
    int b;
    char c;
};
  1. Size is initially 0.
  2. Round to alignment of char (1); size is still 0.
  3. Add size of char (1); size is now 1.
  4. Round to alignment of int (4); size is now 4.
  5. Add size of int (4); size is now 8.
  6. Round to alignment of char (1); size is still 8.
  7. Add size of char (1); size is now 9.
  8. Round to lcm(1,4) (4); size is now 12.

Edit: To address why the last step is necessary, suppose instead the size were just 9, not 12. Now declare struct foo myfoo[2]; and consider &myfoo[1].b, which is 13 bytes past the beginning of myfoo and 9 bytes past &myfoo[0].b. This means it's impossible for both myfoo[0].b and myfoo[1].b to be aligned to their required alignment (4).

like image 95
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 02:11

R.. GitHub STOP HELPING ICE