1

How does __attribute__((__packed__)) work in GCC?

If I have

struct PackedReport
{
  uint16_t FluorScalingFactor[1];
} __attribute__((__packed__));
const static constexpr PackedReport DUMMY_REPORT_PACKED{{ 5 }};

auto begin = std::begin(DUMMY_REPORT_PACKED.FluorScalingFactor);
auto end = std::end(DUMMY_REPORT_PACKED.FluorScalingFactor);

const std::vector<float> expected_matrix(begin, end);

Why does expected_matrix now contain 5,5 and not a just a single 5 as i would expect.
If I remove the __attribute__((__packed__)) it works as expected.
If I use clang it works as expected.

See this minimal godbolt: https://godbolt.org/z/vcxfvoET1
See also godbolt to play around with it with more examples: https://godbolt.org/z/7o9E4snxo

An other observation I made is if I don't store the pointer to begin and end in a variable the resulting std::vector is empty. And I don't understand why this should behave any different since nothing should change these pointers during any of these operations.

const std::vector<float> expected_matrix( std::begin(DUMMY_REPORT_PACKED.FluorScalingFactor), std::end(DUMMY_REPORT_PACKED.FluorScalingFactor));

https://godbolt.org/z/r45qa5fE6

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49
  • 1
    I'm guessing this is undefined behaviour: `std::end` takes a `std::uint16_t(&)[1]`, which is expected to be aligned but isn't (see https://stackoverflow.com/q/27491432, https://stackoverflow.com/a/73154825) – Artyer Mar 03 '23 at 20:00

0 Answers0