0

Let's say that I have a buffer of chars and I want to avoid using memcpy, and access to it through an int* variable:

char buffer[100];
strcpy(buffer,"Hello");
int* __restrict ptr=(int*)buffer;
*ptr= 97;
printf("%s",buffer);

Now this of course prints "a".
Am I allowed to do this without encountering an undefined behaviour?

Johan Bezem
  • 2,582
  • 1
  • 20
  • 47
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
  • 2
    I think you're going in the wrong direction. If anything, the `restrict` is going to make the compiler *more* likely to "break" something since it assumes no aliasing. – Mysticial Nov 16 '12 at 20:39
  • 4
    Indeed. `restrict` makes the aliasing rules much more strict; you're not allowed to alias the pointer **at all** except using pointers "based on" it (in a clever definition of the concept of being "based on"). Not even with pointers to the same type or `char` type pointers. Of course pointers of other types are still not allowed to alias it either. – R.. GitHub STOP HELPING ICE Nov 16 '12 at 20:44
  • So do I still have to use unions? – Ramy Al Zuhouri Nov 16 '12 at 20:49
  • 1
    Note that `__restrict` is a non-standard compiler-specific extension. `restrict` is a standard keyword only in C99 and C11, but *not* in C89 or any current edition of C++. – Adam Rosenfield Nov 16 '12 at 21:30
  • 1
    @RamyAlZuhouri: you never had to use unions. `int val = 97; memcpy(buffer, &val, sizeof(val));` – Steve Jessop Nov 16 '12 at 21:49

1 Answers1

1

Now this of course prints "a".

Well, only on little endian machines.

And strict aliasing would have nothing do with your example as one of the type is char and char may alias anything if the goal of restrict wasn't to increase the number of cases where the compiler may assume that there is no alias, i.e. even when typing information wouldn't prevent it.

And obviously if you want information about __restrict which is in the implementation domain, you should specify the implementation.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143