https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80593
Bug ID: 80593
Summary: GCC 7, aligned_storage and “dereferencing type-punned
pointer will break strict-aliasing rules”
Product: gcc
Version: 7.0.1
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: freddie_chopin at op dot pl
Target Milestone: ---
I've posted this info to the gcc mailing list. Richard Biener suggested opening
a bug report, so here it is.
https://gcc.gnu.org/ml/gcc/2017-05/msg00013.html
Following example code is warning-free on GCC 4.9, GCC 5 and GCC 6. It is also
warning free on some older GCC 7 snapshots (like 7-20170409).
-- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 --
$ cat punning.cpp
template<unsigned _Len, unsigned _Align>
struct aligned_storage
{
union type
{
unsigned char __data[_Len];
struct __attribute__((__aligned__((_Align)))) { } __align;
};
};
aligned_storage<sizeof(int), alignof(int)>::type storage;
int main()
{
*reinterpret_cast<int*>(&storage) = 42;
}
$ g++ -Wall -O2 -c punning.cpp
$
-- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 --
However in the most recent GCC 7 snapshots (including both RCs), it gives a
warning about type punning:
-- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 --
$ g++ -Wall -O2 -c punning.cpp
punning.cpp: In function 'int main()':
punning.cpp:15:35: warning: dereferencing type-punned pointer will break
strict-aliasing rules [-Wstrict-aliasing]
*reinterpret_cast<int*>(&storage) = 42;
^
$
-- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 -- >8 --