简体   繁体   中英

C programming : padding in structure

I am using

processor architecture: x86_64
OS                    : Debian GNU/Linux 9 (stretch) 64-bit
GCC compiler ver.     : 6.3.0

If I compile this code -

struct test {char a; int b;}
test;
printf("%ld", sizeof(test);

then the output is - 8 I assumed it because of 4 bytes padding , I mean 1+3+4 now I tried this code-

struct test{char a; double b;} 
test;

and this gave me 16 bytes, then I thought, may be it is because of 8 bytes padding, ie- 1+7+8 now when I tried this code -

struct test{char a; long double b; char c;}
test;

this gave me 48 bytes

In my system using gcc , int = 4 byte, double = 8 byte, char = 1 byte ,long double = 16 byte.

My question is how this works? Why not a uniform padding?

You changed the pattern with your third structure. If you had this third structure instead, you would have gotten numbers consistent with the pattern for the first two:

struct A { char a; int b; };         // 1 +  3 +  4 =  8
struct B { char a; double b; };      // 1 +  7 +  8 = 16
struct C { char a; long double b; }; // 1 + 15 + 16 = 32

Now, when you put another char after the long double , you only need one more byte for that, but the compiler adds another 15 bytes of padding:

struct D { char a; long double b; char c; }; // 1 + 15 + 16 + 1 + 15?!

I think the question you're really trying to ask is, why does it do that? It does that because of arrays. The C standard says that there can never be any padding in between the elements of an array. But for the interior padding to do its job of keeping b properly aligned to 16 bytes, struct D must itself be aligned to 16 bytes. If struct D were 33 bytes long, the second element of an array struct D dee[2] would be misaligned. So the compiler must insert more padding at the end of struct D to make its size a multiple of its 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