C++ Data Member Alignment and Array Packing

Adam Holmberg picture Adam Holmberg · Nov 4, 2009 · Viewed 10k times · Source

During a code review I've come across some code that defines a simple structure as follows:

class foo {
   unsigned char a;
   unsigned char b;
   unsigned char c;
}

Elsewhere, an array of these objects is defined:

foo listOfFoos[SOME_NUM];

Later, the structures are raw-copied into a buffer:

memcpy(pBuff,listOfFoos,3*SOME_NUM);

This code relies on the assumptions that: a.) The size of foo is 3, and no padding is applied, and b.) An array of these objects is packed with no padding between them.

I've tried it with GNU on two platforms (RedHat 64b, Solaris 9), and it worked on both.

Are the assumptions above valid? If not, under what conditions (e.g. change in OS/compiler) might they fail?

Answer

ThePosey picture ThePosey · Nov 4, 2009

It would definitely be safer to do:

sizeof(foo) * SOME_NUM