1

I got the following struct:

struct Packet
{
    short PacketSize;
    short Type;
};

struct SizeValidity
{
    short SizeEnc;
};

struct SendEncSecureCode
{
    Packet header;
    short EncSecurityToken;
    int lTime;
    SizeValidity ending;
};

And on my code i want to get the size of the struct with the sizeof operator like this:

SendEncSecureCode sendpacket;
sendpacket.header.PacketSize = sizeof SendEncSecureCode;

Problem is i always get size 0x10 instead of 0x0C i am specting, so i change the INT type to DWORD and still the same problem, later i try with DWORD32 and still the same, the compiler is setting it as 8 bytes. I am working on VC11 Beta and the soft is aim to x86 not x64. Thanks

ffenix
  • 543
  • 1
  • 5
  • 22
  • `sizeof SendEncSecureCode` needs brackets around `SendEncSecureCode` since it's a type. If that's compiling, I'd recommend changing it. – chris Jul 26 '12 at 04:49
  • brackets arround the struct name gives me error that is not a variable... – ffenix Jul 26 '12 at 04:51
  • 1
    possible duplicate of [structure padding and structure packing](http://stackoverflow.com/questions/4306186/structure-padding-and-structure-packing) – AndersK Jul 26 '12 at 04:52

2 Answers2

3

This is called padding. The compiler pads the space between the different members of the structure with zero bytes to better-align the members to addresses that can be read quicker by the CPU. You can (but should not unless you have a very good reason) override this behavior with the pack pragma:

#pragma pack(push, 0)
struct {...};
#pragma pack(pop)

This forces the padding for this struct to be zero bytes. You can change the zero around.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mahmoud Al-Qudsi
  • 28,357
  • 12
  • 85
  • 125
0

To get the size you're expecting, you can tell the compiler to use 1-byte packing:

#pragma pack(push, 1)
struct Packet
{
    short PacketSize;
    short Type;
};

struct SizeValidity
{
    short SizeEnc;
};

struct SendEncSecureCode
{
    Packet header;
    short EncSecurityToken;
    int lTime;
    SizeValidity ending;
};
#pragma pack(pop)

Please see http://vcfaq.mvps.org/lang/11.htm

craig65535
  • 3,439
  • 1
  • 23
  • 49