This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: dereferencing type-punned pointer will break strict-aliasing rules
- From: Martin Sebor <msebor at gmail dot com>
- To: Marcel Behlau <marcel dot behlau at elfin dot de>, gcc-help at gcc dot gnu dot org
- Date: Fri, 22 Jan 2016 10:45:03 -0700
- Subject: Re: dereferencing type-punned pointer will break strict-aliasing rules
- Authentication-results: sourceware.org; auth=none
- References: <56A0DEE0 dot 4030003 at elfin dot de>
On 01/21/2016 06:36 AM, Marcel Behlau wrote:
Hi,
i wan't to create aliase (symbolic name and explizit type) for the
elements of an char-array. Unfortunately my gcc produce the warning
"dereferencing type-punned pointer will break strict-aliasing rules", if
i use -O2 or bigger. Since i set -Werror, the warning will become an error.
I attached an example to this mail. To compile and generate the problem,
i use "gcc -O2 -Werror -Wall main.cpp".
I found an workaround (without using pragma, or somethink else), with
it's included in the code, too. To activate, pass an extra "-DWorking"
to the gcc-Command. The workaround is working, but using an pointer is
ugly.
The language rules only define the effects of accessing an object
using an lvalue of either a compatible type, or [unsigned] char.
In the example, casting the address of the data array to a pointer
to struct Ec would make it possible to access the data object using
an incompatible type (this is called type punning). If that were
to happen, the compiler may not be able to detect such an access
and so it warns about it at the point the address is converted to
the destination type.
While strictly speaking on the fringes of the rules of the language,
you may be able to accomplish what you're trying to do by defining
the two objects in an anonymous union:
class ClassZero
{
public:
char* pointer;
union {
char data[8];
struct Ec ec;
};
ClassZero() : pointer(data), ec0() { }
...
Then both ec and data share the same space and can be accessed
as if they were distinct members of ClassZero.
Martin