1

My understanding of strict aliasing is that we cannot (with few exceptions like char*) use two different types of pointers to access/dereference the same region of memory. I have a char buffer and a pointer to a struct Foo, and i want to "save" this pointer into the buffer so that elsewhere I just retrieve the pointer and use it. Like this:

Foo* f =//pointer to some real Foo object
char buf[N];
memcpy(buf, &f, sizeof(Foo*));

then later:

Foo* f2 = *(Foo**) &buf;
f2->bla;

This breaks aliasing as pointed out below because buf is an array of characters and we treat it as a Foo** and dereference that. Is there a way to get my Foo object through with the pointer only through buf or do I have to copy all of Foo into the buffer?

Palace Chan
  • 8,845
  • 11
  • 41
  • 93

1 Answers1

0

Because aliasing rules only allow you to access an object through its own type (including its signed / unsigned variant) or through a character type.

buf is an array of character and you are accessing it through a type not in the list of allowed types above.

ouah
  • 142,963
  • 15
  • 272
  • 331