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]

Re: strict aliasing: how to swap pointers


Evan Jones wrote:
> Andrew Haley wrote:
>> so, this:
>>
>>   int *sp = &int_var;
>>   void *vp = sp;
>>   *(short*)vp = 22;
>>
>> is undefined behaviour, and may well not do what you want. 
> 
> Ignoring platform specific issues like byte order and size, is it safe
> to use memcpy instead? Example:
> 
> int *sp = &int_var;
> void *vp = sp;
> short value = 22;
> memcpy(vp, &value, sizeof(value));

This is okay, albeit non-portable.

> In my experiments with strict aliasing and GCC, replacing accesses like
> this with memcpy resolves the problem, even when GCC inlines the memcpy
> into a simple load/store. It seems to me that this should be okay, since
> the write through a void pointer is permitted to alias anything?

It's okay if and only if you're not doing anything with pointers to
incompatible types.

> Or is the only safe way to use the mayalias attribute?
> 
> I think I'm starting to understand why many people insist on using
> -fno-strict-aliasing.

Why not write in Standard C?  I don't understand this determination to
try to subvert the type system via pointers.  What application actually
needs it?  If you *really* need to access the bits in a float you can
do that via a union.

Andrew.


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