Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With strict aliasing in C++11, is it defined to _write_ to a char*, then _read_ from an aliased nonchar*?

There are many discussions of strict aliasing (notably "What is the strict aliasing rule?" and "Strict aliasing rule and 'char *' pointers"), but this is a corner case I don't see explicitly addressed.

Consider this code:

int x;
char *x_alias = reinterpret_cast<char *>(&x);
x = 1;
*x_alias = 2;  // [alias-write]
printf("x is now %d\n", x);

Must the printed value reflect the change in [alias-write]? (Clearly there are endianness and representation considerations, that's not my concern here.)

The famous [basic.lval] clause of the C++11 spec uses this language (emphasis mine):

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • ... various other conditions ...
  • a char or unsigned char type.

I can't figure out whether "access" refers only to read operations (read chars from a nonchar object) or also to write operations (write chars onto a nonchar object). If there's a formal definition of "access" in the spec, I can't find it, but in other places the spec seems to use "access" for reads and "update" for writes.

This is of particular interest when deserializing; it's convenient and efficient to bring data directly from a wire into an object, without requiring an intermediate memcpy() from a char-buffer into the object.

like image 934
Dan E. Avatar asked Oct 14 '25 15:10

Dan E.


1 Answers

is it defined to _write_ to a char*, then _read_ from an aliased nonchar*?

Yes.

Must the printed value reflect the change in [alias-write]?

Yes.

Strict aliasing says ((un)signed) char* can alias anything. The word "access" means both read and write operations.

like image 163
emlai Avatar answered Oct 17 '25 03:10

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!