Struct memory allocation, memory allocation should

2019-08-28 21:50发布

问题:

struct x
{
  char b;
  short s;
  char bb;
};


int main()
{
 printf("%d",sizeof(struct x));
}

Output is : 6

I run this code on a 32-bit compiler. the output should be 8 bytes.

My explanation --> 1. Char needs 1 bytes and the next short takes multiple of 2 so short create a padding of 1 and take 2 bytes, here 4 bytes already allocated. Now the only left char member takes 1 byte but as the memory allocates is in multiple of 4 so overall memory gives is 8 bytes.

回答1:

The alignment requirement of a struct is that of the member with the maximum alignment. The max alignment here is for short, so probably 2. Hence, two for b, two for s, and two for bb gives 6.



回答2:

The C struct memory layout is completely implementation-specific and you can't assume all of this.

Also, in the typical alignment of C structs a struct like this:

struct MyData
{
    short Data1;
    short Data2;
    short Data3;
};

will also have sizeof = 6 because if the type "short" is stored in two bytes of memory then each member of the data structure depicted above would be 2-byte aligned. Data1 would be at offset 0, Data2 at offset 2, and Data3 at offset 4. The size of this structure would be 6 bytes.

See https://en.wikipedia.org/wiki/Data_structure_alignment



标签: c memory struct