https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80334
Bug ID: 80334 Summary: Segfault when taking address of copy of unaligned struct Product: gcc Version: 7.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: jagerman at jagerman dot com Target Milestone: --- I am getting a segfault with g++ 7 when trying to copy an unaligned struct into an aligned variable when the struct contains a member with alignment greater than 8 (on my amd64 architecture). I boiled my code down into the following simplified program which exhibits the segfault under a recent g++ 7 snapshot (requires compiling with -O2 or above to trigger): test.cpp ===== #include <iostream> struct A { alignas(16) char c; }; struct B { A unpacked; char d; } __attribute__((packed)); int main() { std::cout << "sizeof(A) = " << sizeof(A) << ", sizeof(B) = " << sizeof(B) << "\n"; alignas(16) B b[3]; for (int i = 0; i < 3; i++) b[i].unpacked.c = 'a' + i; for (int i = 0; i < 3; i++) { std::cout << "i=" << i << "; copying..." << std::endl; auto a = new A(b[i].unpacked); std::cout << "copied value = " << a->c << std::endl; } } ===== If I change the `alignas(16)` on the member in `struct A` to `alignas(8)` or `alignas(4)` there is no segfault; there also is no segfault under -O0 or -O1, or under g++ 6. (The `alignas(16) char` was a `long double` in the original code, which has alignof == 16). The alignas(16) on the array in main is just there to force alignment on the first element of `b`: with that alignment, the *first* copy succeeds because the `unpacked` member happens to be correctly aligned; the call in the second iteration of the loop (when the member isn't aligned) triggers the segfault.