3

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.)

Community
  • 1
  • 1
phranck
  • 61
  • 6

2 Answers2

3

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.

gaige
  • 17,263
  • 6
  • 57
  • 68
0

Look at structure padding, alignment. There are ways to force alignment in certain compilers:

typedef struct LMWinData {
    UInt8   itemTypeID;
    UInt16  serviceID;
    UInt16  methodID;
} LMWinData __attribute__ ((aligned (1)));