memory allocation for structures elements

前端 未结 7 1176
故里飘歌
故里飘歌 2021-01-19 05:14

Hi I am having difficulties in understanding about how the memory is allocated to the structure elements.

For example if i have the below structure and the size of c

相关标签:
7条回答
  • 2021-01-19 06:11

    It seems that on your system, double has to have the alignment of 8.

    struct temp {
        int a;     // size is 4
        // padding 4 bytes
        double b;  // size is 8
        char c;    // size is 1
        // padding 7 bytes
        double d;  // size is 8
        int e;     // size is 4
        // padding 4 bytes
    }; 
    // Total 4+4+8+1+7+8+4+4 = 40 bytes
    

    Compiler adds an extra 4 bytes to the end of struct to make sure that array[1].b will be properly aligned.

    Without end padding (assuming array is at address 0):

    &array[0]   == 0
    &array[1]   == 36
    &array[1].b == 36 + 8 == 44  
    44 % 8 == 4  ->  ERROR, not aligned!
    

    With end padding (assuming array is at address 0):

    &array[0]   == 0
    &array[1]   == 40
    &array[1].b == 40 + 8 == 48
    48 % 8 == 0  ->  OK!
    

    Note that sizes, alignments, and paddings depend on target system and compiler in use.

    0 讨论(0)
提交回复
热议问题