> 
> I have code that goes something like this:
> 
> char *foo(char *buf){
>     *buf++ = 42;
>     *((short*)buf) = 0xfeed;
>     buf += 2;
>     *((int*)buf) = 0x12345678;
>     buf += 4;
>     *((int*)buf) = 0x12345678;
>     buf += 4;
>     return buf;
> }

This does violate C aliasing rules.

Here is how I would write it so you can get the best results:

char *foo(char *buf)
{
  short temp;
  int temp1;
  *buf++=42;
  temp = 0xfeed;
  memcpy(buf, &temp, sizeof(temp));
  buf+=sizeof(temp);
  temp1 = 0x12345678;
  memcpy(buf, &temp1, sizeof(temp1));
  buf+=sizeof(temp1);
  temp1 = 0x12345678;
  memcpy(buf, &temp1, sizeof(temp1));
  buf+=sizeof(temp1);
  return buf;
}

As using memcpy does not cause a violation of the aliasing rules.

And does the correct thing:
        lis 11,0x1234
        li 0,42
        li 9,-275
        ori 11,11,22136
        stb 0,0(3)
        sth 9,1(3)
        stw 11,7(3)
        stw 11,3(3)
        addi 3,3,11


-- Pinski

Reply via email to