Understanding the limitations of memory alignment and byte padding in C

I have the following code snippet.

#include<stdio.h>
int main(){
    typedef struct{
        int a;
        int b;
        int c;
        char ch1;
        int d;
    } str;
    printf("Size: %d \n",sizeof(str));
    return 0;
}

Which gives a conclusion as follows

Size: 20

I know that size is structurelarger than summing component sizes structuredue to padding added to satisfy memeory alignment constraints. I want to know how the decision was made about how many fill bytes should be added. What does it depend on? Does it depend on the processor architecture? And it also depends on the compiler? I am using a 64 bit processor and gcccompiler here. How will the output change if these parameters change. Please explain some example, please.

I know there are similar questions in StackOverflow, but they do not fully explain these memory alignment limitations.

+4
3

. , :

C x86 ARM . , , char, ; , 2- , 4 ints floats , 4, 8- , 8. unsigned .

, , : sizeof(str) = 4 (4 bytes for int) + 4 (4 bytes for int) + 1 ( 1 byte for char) + 7 (3 bytes padding + 4 bytes for int) = 20

, int , 4 . , int 4 ( ). .

+4

? ? ?

CPU, .

+1

, , , , , wikipedia , .

64- Linux-, , , , ( ), :

int float 4 ( , 4)

char bool 1 ( )

double pointers 8

The best way to avoid padding is to put your fields from the largest to the smallest (when there are only base fields)

When there are folded fields, it’s a little harder for me to explain here, but I think you can understand this in your article

0
source

All Articles