Usage of __attribute__((aligned(4), packed)) with structures in C

51 Views Asked by At

I want to use the structure to store some data and then transfer it via DMA. However, the specifics of the periphery require alignment of the initial address of the structure along the 4-byte boundary. I don't understand why using the alignment attribute in different places causes the packed structure to be resized by 1 byte.

I wrote simple example to represent this situation.

#include <stdio.h>
#include "stdint.h"

// Version with aligned attribute
struct packet_v1 
{
    uint8_t uid;
    uint8_t flag;
    uint8_t comm;
    uint32_t a;
    
} __attribute__((packed, aligned(4)));

// Version without alignment 
struct packet_v2
{
    uint8_t uid;
    uint8_t flag;
    uint8_t comm;
    uint32_t a;
    
} __attribute__((packed));


struct packet_v1 pkt1;
struct packet_v2 pkt2 __attribute__((aligned(4)));


int main()
{
    printf("Align v1: %lu, size: %lu\r\n", (uintptr_t)&pkt1 % 4, sizeof(pkt1));
    printf("Align v2: %lu, size: %lu\r\n", (uintptr_t)&pkt2 % 4, sizeof(pkt2));
    
    return 0;
}

Output:

Align v1: 0, size: 8
Align v2: 0, size: 7
1

There are 1 best solutions below

0
Barmar On BEST ANSWER

struct_v1 has a padding byte at the end, so that an array of structures will have each element aligned to a 4-byte boundary, as required by aligned(4).

struct_v2 has no padding byte, so that an array of structures will be packed as tightly together as possible. There's no need to align each array element the same.