This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Aliasing rules and the -f[no-]strict-aliasing switches


Hi!

Can anyone please explain what -f[no-]strict-aliasing and
-W[no-]strict-aliasing do?  (Yes, gcc accepts -Wno-strict-aliasing!)  I'm
experiencing some mild nausea because of type-punning in a library I'm
maintaining.  Gcc's documentation is not very clear, talking only about
types being "almost the same".  And unfortunately I have no copy of the
holy standard lying around..  Also, Google appears to turn up only
confused and confusing arguments, to this issue...  :-(

I was under the impression that pointers to some data structures are
"almost the same", but apparently this is wrong:

class Base {
public:
    int x;
};

class Derived : public Base {
public:
    Derived() { x = 24; }
    virtual ~Derived() {}  // (1)
};

class Manager {
public:
    union {
	void* pointer;
	Base* basepointer;
    };
};


#include <iostream>
using namespace std;
int main()
{
    Derived* mp = new Derived;
    Manager obj;
    obj.pointer = mp; // (2)
    cout << mp->x << endl;
    cout << obj.basepointer->x << endl;
}

When compiled with GCC 3.x or 4.x, this results in:
24
134515352

With GCC 2.95, it resulted in:
24
24

Okay, removing the vtable in Derived (1) or adding one in Base (by adding
a virtual dtor) appears to fix the program.  Obviously, assigning to
basepointer, as opposed to pointer (2) fixes it, too.

But: As it stands, is the program really wrong?  And: Why does
-f[no-]strict-aliasing not make a difference.  And should not
-Wstrict-aliasing issue a warning?

Regards
   -richy.
-- 
Richard B. Kreckel
<http://www.ginac.de/~kreckel/>


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]