Re: dereferencing type-punned pointer will break strict-aliasing rules

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux