Click to See Complete Forum and Search --> : sizeof question


mop
October 4th, 2002, 06:54 AM
I'm at a lost on why the sizeof NODE per call below is 8.
My thoughts are it should be 5. considering the sizeof NODESTATE is 4 and the sizeof unsigned char is 1. Why is it 8?




# include <iostream>
using namespace std;

typedef enum
{
NOT_PRESENT = 0u,
POWER_OFF,
POWER_ON,
SILENT
} NODESTATE;

typedef struct
{
unsigned char address;
NODESTATE state;
} NODE;

static NODE NodeMap [] =
{
0, NOT_PRESENT,
0, NOT_PRESENT
// 0, NOT_PRESENT
};

int main(void)
{

printf( "%s%d\n", "sizeof NodeMap = ", sizeof(NodeMap));
printf( "%s%d\n", "sizeof NODE = ", sizeof(NODE));
printf( "%s%d\n", "sizeof unsigned char = ", sizeof(unsigned char));
printf("%d\n",sizeof(NODESTATE));

return 0;
}


RESULT :

sizeof NodeMap = 16
sizeof NODE = 8
sizeof unsigned char = 1
4

Graham
October 4th, 2002, 07:45 AM
Probably because the compiler is aligning your structures on a 4-byte boundary.

Andreas Masur
October 4th, 2002, 08:09 AM
The size is different from five since the compiler will align this structure. This is called structure alignment. Fundamental types (int, float etc.) are stored in memory at addresses that are multiples of their length. CPU are optimized to access memory aligned this way. The compiler will therefore add some extra bytes between the fields of a structure to ensure that all of them that require alignment are properly aligned. Same applies to the instances of that structure. Therefore the compiler might add also some extra bytes at the end to ensure that arrays of this structure also get aligned properly.

The whole thing is based on the implementation, meaning that every compiler vendor is free to use the way of alignment and padding to fit their compiler the best. So you cannot rely on a standard alignment. Visual C++ compilers traditionally use 8-byte alignment as the standard value. Others might only use 4-byte alignment.

Nevertheless, that is why the size of your structure differs from your calculated one...

cup
October 4th, 2002, 08:17 AM
If you are using VC++, try adding #pragma pack(n) where n can be 1, 2, 4,8, 16. The results vary a lot.