Re: strict aliasing: how to swap pointers

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

 



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));

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?

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.

Evan

--
Evan Jones
http://evanjones.ca/

[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