Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Data Member Alignment and Array Packing

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?

like image 776
Adam Holmberg Avatar asked Nov 04 '09 20:11

Adam Holmberg


1 Answers

It would definitely be safer to do:

sizeof(foo) * SOME_NUM
like image 176
ThePosey Avatar answered Oct 03 '22 17:10

ThePosey