This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Compiler assumes array addresses are aligned for structs declared with __attribute__((packed))

If I have a struct declared like the following:

volatile struct {
    uint8_t foo;
    int16_t bar[1];
} __attribute__((packed)) foobar;

The code emitted uses LDRSH to access bar[0] and causes a hardfault at runtime. But If I were to declared it using the __packed qualifier:

__packed volatile struct {
    uint8_t foo;
    int16_t bar[1];
} foobar;

Then the compiler correctly recognizes the potential misalignment and emits LDRB instead. Is this the expected behavior? I'm using uVision v5.17 with Armcc v5.06 update 1 (build 61). Thanks.

Parents
  • It seems strange if the compiler supports a construct where it does pack the data but at the same time accesses the data with instructions that does not support packed data.

    If you had instead used a pointer, then I would have assumed that the compiler didn't support one of the two ways of specifying packed data.

    Or might something happen where the compiler do not support one of the constructs but the attribute survives all the way down to the linker so the linker takes non-packed data and links it to an odd address?

Reply
  • It seems strange if the compiler supports a construct where it does pack the data but at the same time accesses the data with instructions that does not support packed data.

    If you had instead used a pointer, then I would have assumed that the compiler didn't support one of the two ways of specifying packed data.

    Or might something happen where the compiler do not support one of the constructs but the attribute survives all the way down to the linker so the linker takes non-packed data and links it to an odd address?

Children