Search code examples
c

Align array of structs within 4K boundary


I am trying to reformat some code that uses a struct aligned by a 4096 byte boundary. The struct is basically a 2d array at each point is 2 different uint16 with some padding at each row. The way the structs are declared are as follows

frame TemporaryFrame0 __attribute__ ((aligned(4096)));
frame TemporaryFrame1 __attribute__ ((aligned(4096)));
frame TemporaryFrame2 __attribute__ ((aligned(4096)));

I am wanting to declare it as

frame TemporaryFrame[3] __attribute__ ((aligned(4096)));

but when I declare as such, it is not stored in memory properly/ the same. The struct is as such

typedef struct frame frame;
struct frame {
    u8 byte_offset[32];
    row row[FRAME_ROW_SIZE];
};

I have also tried to declare the struct as follows with no benefit.

typedef struct frame frame;
struct frame {
    u8 byte_offset[32];
    row row[FRAME_ROW_SIZE];
}__attribute__ ((aligned(4096)));

Solution

  • frame TemporaryFrame[3] __attribute__ ((aligned(4096))); says to make the array TemporaryFrame aligned. Its elements are whatever size they are and are necessarily contiguous in memory. If the size of frame is X, the address of TemporaryFrame[1] is X bytes beyond the address of TemporaryFrame[0], and it is not 4096-byte aligned unless X is a multiple of 4096.

    To make the elements aligned, define struct frame to be aligned:

    struct frame {
        u8 byte_offset[32];
        row row[FRAME_ROW_SIZE];
    } __attribute__ ((aligned(4096)));
    

    If you do not want to change the definition of struct frame, you can use an enclosing structure to provide the alignment, but you will have to add extra code to refer to the structure member:

    struct { struct frame f __attribute__ ((aligned(4096))); } TemporaryFrame[3];
    
    …
    // Later, where TemporaryFrame[i] would be used, use instead:
    TemporaryFrame[i].f