Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
I have a simple C struct defined like this:
typedef struct LMWinData {
UInt8 itemTypeID;
UInt16 serviceID;
UInt16 methodID;
} LMWinData;
Later in code I define a variable of this type like this one:
LMWinData lmWinData;
Now, if I print out the size of this variable:
NSLog(@"data has size of %lu bytes", sizeof(lmWinData));
I don't get the value (5 bytes) as expected. I get a size of 6 bytes instead.
So, what's wrong here?
Thanks a lot!
(I'm using Mac OS X Lion.)
You are seeing an alignment issue here. This can be a tricky problem when dealing with compilers that are attempting to make software access locations efficiently. In particular, you have a structure wherein two 16-bit integers follow an 8-bit, causing the 16-bit integers to start at an odd location, which is generally slow.
However, there are cases when this is necessary, and the clang/llvm method for controlling alignment and padding is __attribute__((packed)).
or, to use on your structure:
typedef struct LMWinData {
UInt8 itemTypeID;
UInt16 serviceID;
UInt16 methodID;
} __attribute__((packed)) LMWinData;
I think this also works in modern gcc, as well.
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