Why doesn't structural laying work properly?

#include<stdio.h> struct A { char c; double e; int s; }A; int main() { printf("%u\n", sizeof(A)); return 0; } 

He outputs 16 . Shouldn't it be 24 if we look at the internal laying of the structure and the laying of the structure as a whole?

I am compiling code on Ubuntu 14.04 32 bit with GCC 4.8.2 .

+6
source share
1 answer

In your calculations, it is assumed that double should be aligned by 8 bytes. This does not apply to all architectures.

On 32-bit x86 Linux with GCC, double will default to 4 byte alignment. You can change this with the -malign-double flag to make it 8-byte.

So, a layout assuming default values ​​on 32-bit x86 Linux:

 char // 1 byte // 3 byte padding double // 8 bytes int // 4 bytes 

So, a total of 16 bytes, with 3 bytes of padding in the middle.

In a Wikipedia article, data structure alignment has size / alignment numbers for various types on 32-bit x86 and 64-bit x86_64 in several compilers / environments.

+12
source

Source: https://habr.com/ru/post/985927/


All Articles