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));
std::end
takes astd::uint16_t(&)[1]
, which is expected to be aligned but isn't (see stackoverflow.com/q/27491432, stackoverflow.com/a/73154825)