views:

136

answers:

2

I have a structure I would like to optimize the footprint of.

typedef struct dbentry_s {
   struct dbentry_s* t_next;
   struct dbentry_s* a_next;
   char *t;
   char *a;
   unsigned char feild_m;
   unsigned char feild_s;
   unsigned char feild_other;
} dbentry;

As I understand it, the compiler creates structures in memory as you define them. So larger types should be declared first so the small types can fill in the alignment holes.

I have read the WikiPedia article on data structure alignment and other articles on the issue. http://en.wikipedia.org/wiki/Data_structure_alignment

But I'm still not sure, is my current ordering the most optimal or am I missing something?

Note: My compiler doesn't support "#pragma pack"

+5  A: 

No, that should be the most optimal order based on common compiler behavior (keeping in mind that the standard does not actually mandate how the structures are packed with respect to the spaces between the elements, although it does guarantee the order is as specified: see '6.2.5 Types' of the latest draft C1x-n1425).

You have all your pointers up the front and all your characters down the back, so you'll probably find that, with a four-byte pointer size you'll end up with a 19- or 20-byte structure.

You can easily check this by inserting the following lines in your code:

printf ("Size of dbentry* is %d\n", sizeof (struct dbentry_s*));
printf ("Size of char*    is %d\n", sizeof (char*));
printf ("Size of uns char is %d\n", sizeof (unsigned char));
printf ("Size of stucture is %d\n", sizeof (dbentry));

The reason I've put in all the sizeof checks is to ensure you have full information. I'm well aware the sizeof(char) is always 1.

paxdiablo
Believe this guy in packing issues, for him bears the name "packs-diablo"!
Pavel Shved
The standard does actually mandate that the fields are placed in the order that they're declared.
caf
@caf, I didn't actually see order as part of packing, instead thinking of packing as simply the spaces (or lack thereof) between elements. But it's a good point so I'll modify the answer to suit.
paxdiablo
+1  A: 

You might be interested in using pahole and/or Cruncher#. Both are tools that analyze the layout of structures in memory.

Reference: original Maciej Sinilo blog post about Cruncher#.

Gregory Pakosz
Oh my, this one also alludes to "pack" in his name!
Michael Krelin - hacker
I'm sorry I didn't get it :/
Gregory Pakosz
Pak-osz. Do you pronounce it Pa-kosz?
Hans Passant
Oh that, right. About the pronunciation in French it's "pak - oz" and in Polish it must be "pak - och" I think.
Gregory Pakosz
So, you must know a thing about packing. (See Pavel's comment to the other guy).
Michael Krelin - hacker