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?
It would definitely be safer to do:
sizeof(foo) * SOME_NUM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With