memory alignment __attribute__( ( aligned ( 8 ) ) )

前端 未结 3 1447
死守一世寂寞
死守一世寂寞 2020-12-30 06:21

I got a program in a book

#include 
int main( )
{
    struct data
    {
        int a    __attribute__( ( aligned ( 8 ) ) ) ;
        char ch          


        
3条回答
  •  庸人自扰
    2020-12-30 07:16

    A sizeof is always a multiple of largest alignment, as it is actually reports 'step' in chars in array of given type which include padding as between members so padding between array elements required to align them.

    Memory layout of struct data will look like this:

     00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 ... <--offset
    |                                               |
    |          struct data   (element [0])          |      (element [1])
    |                                               |
    |     a     |ch|::::::::|     s     |:::::::::::|     a     |ch|::::...
    |                                               |
    |<----------- sizeof(struct data) ------------->|
    
    |::::| is padding
    
    • a is at offset 0 which is obviously a multiple of 8;
    • ch is at offset 4 which is (also obviously) a multiple of 1;
    • s is at offset 8 which is multiple of 4;
    • sizeof(struct data) is equal to offset of [1] (16) which required to be multiple of max(8,1,4) = 8

提交回复
热议问题