Why are we reading incorrect length ?

struct SOME_STRUCT
{
  unsigned short objectId;
  unsigned long  length;
};

We read sizeof(SOME_STRUCT) from buffer.
sizeof(SOME_STRUCT) - Not sure why the lenght is Eight bytes when the structure contains a short and a long.

The data in the buffer is as follows:

01 00 00 08 00 00 00 00 00 00

We thought we were reading six bytes from the buffer but we're reading eight bytes from it.
objectId is 0x0001
length is 0x00000000

We're using Keil compiler Armcc.Exe V4.1.0.894

It looks like we have some kind of alignment issue? Does this compiler only read from word aligned addresses ? What is the root cause of the problem ? Do we need some kind of PACK or packed keyword so compiler reads six bytes from the buffer instead of eight ?

Parents
  • Most processors have quite high alignment needs for speed reasons. The second value is a 32-bit value - for a 32-bit processor. So it's aligned modulo 4 bytes. And the size of a struct is affected by the member with the highest align requirement so switching place of the two members wouldn't have dropped the size to 6 bytes - only an 8 byte large struct can be used in an array with maintained align for every element of the array.

    You could play with a packed struct, but consider writing own code to pack/unpack. Then most of your code could be small and fast - with packed data, all accesses must contain lots of extra processor instructions.

Reply
  • Most processors have quite high alignment needs for speed reasons. The second value is a 32-bit value - for a 32-bit processor. So it's aligned modulo 4 bytes. And the size of a struct is affected by the member with the highest align requirement so switching place of the two members wouldn't have dropped the size to 6 bytes - only an 8 byte large struct can be used in an array with maintained align for every element of the array.

    You could play with a packed struct, but consider writing own code to pack/unpack. Then most of your code could be small and fast - with packed data, all accesses must contain lots of extra processor instructions.

Children
More questions in this forum