Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading