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


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 Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]