I'm trying to grok what exactly you get from the easement on aligned variables in C99:
Exception to strict aliasing rule in C from 6.5.2.3 Structure and union members
Does it give you carte blanche on casting to that union, if the original write was done through a pointer to one of the aligned structs as below?
#include <stdio.h>
#include <stdlib.h>
struct Foo { char t; int i; };
struct Bar { char t; float f; };
union FooBar {
struct Foo foo;
struct Bar bar;
};
void detector(union FooBar *foobar) {
if (((struct Foo*)foobar)->t == 'F')
printf("Foo %d\n", ((struct Foo*)foobar)->i);
else
printf("Bar %f\n", ((struct Bar*)foobar)->f);
}
int main() {
struct Foo *foo = (struct Foo*)malloc(sizeof(struct Foo));
struct Bar *bar = (struct Bar*)malloc(sizeof(struct Bar));
foo->t = 'F';
foo->i = 1020;
detector((union FooBar*)foo);
bar->t = 'B';
bar->f = 3.04;
detector((union FooBar*)bar);
return 0;
}
Note in the second call, t
was written as a "bar's t" but then in order to discern which kind it has, the detector reads it as a "foo's t"
My reaction coming from C++ would be that you'd only be able to do it if you had "allocated it as a FooBar union in the first place". It's counter-intuitive to me to imagine this as legal, but for dynamic allocations in C there's no such thing. So if you can't do that, what exactly can you do with a dynamic memory allocation such as the above under this exception?