Re: strict aliasing: how to swap pointers

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

 



Evan Jones <evanj@xxxxxxx> 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.


[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