strict aliasing: how to swap pointers

Sergei Organov
Wed Apr 30 21:49:00 GMT 2008

Evan Jones <evanj@MIT.EDU> writes:
> 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));

It's safe w.r.t. aliasing rules, provided memcpy() implementation is
safe, and chances are high that memcpy() is safe ;)

> 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?

AFAIK, there is no way to write through void pointer ;) You need to cast
to something else before writing anyway.

It's "[[un]signed] char *" that you can use to write to and read from
anything. This is what makes it possible to implement memcpy() in C/C++.

-- Sergei.

More information about the Gcc-help mailing list