简体   繁体   中英

Struct memory allocation, memory allocation should be in multiple of 4

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM