1

I have an issue with C++ and VS-2015 with the next structure:

struct HEADER
{
    char BRI;
    char crv_lenght;
    __int16 crv;
    char messagetype;
};

The size of this structure is 5 bytes, but when it is converted to an array of bytes the resulting array has a size of 6 bytes.

The way that i used to convert the struct to array is using memcpy is:

HEADER hdr;

hdr.BRI = 0x08
hdr.crv_lenght =0x02;
hdr.crv = 0;
hdr.messagetype = 0x04;

char* buffer;
buffer = new char[sizeof(HEADER)];
memcpy(buffer, tmpBuff, *size);

After coverting the struct to an array, the buffer shows an extra byte (0xcc), that appears after the crv field:

DEBUG DATA HEX (Bytes 1-6) [08 02 00 00 cc 04]

But, when i change the struct to use char[2] instead of __int16, like this:

struct HEADER
{
    char BRI;
    char crv_lenght;
    char crv[2];
    char messagetype;
};

The resulting array size is 5 bytes, removing the extra byte:

DEBUG DATA HEX (Bytes 1-5) [08 02 00 00 04]

I found a way to "fix" this issue is using the directive #pragma pack(push,1) and #pragma pack(pop), like the sample below:

#pragma pack(push,1)
struct HEADER
{
    char BRI;
    char crv_lenght;
    __int16 crv;
    char messagetype;
};
#pragma pack(pop)

So, the main questions is: For the compiler of C/C++ with VS-2015, this behaivor is expected and why it needs to use the #pragma pack directive?

Additional information:

  • The OS Windows 2012 r2.
  • Visual Studio 2016, version 14.0.25431.01 Update 3.
  • Language: C++11
  • The project type is a Console App.
  • This behavior appears in both x86 and x64.
Jorge Omar Medra
  • 978
  • 1
  • 9
  • 19

0 Answers0