Say I have two structs: object
and widget
:
struct object {
int field;
void *pointer;
};
struct widget {
int field;
void *pointer;
};
And a function:
void consume(struct object *obj)
{
printf("(%i, %p)\n", obj->field, obj->pointer);
}
I'm aware that if I try and do:
struct widget wgt = {3, NULL};
consume(&wgt);
I would violate the strict aliasing rule, and thus have an undefined behaviour.
As far as I understand, the undefined behaviour results from the fact that the compiler may align the struct fields differently: that is, padding fields to align with address boundaries (but never changing fields order, since the order is guaranteed to be respected by the standard).
But what if the two structs are packed? Will they have the same memory layout? Or, in other words, does the above consume()
still have an undefined behaviour (despite the persistent compiler warning)?
Note: I used struct __attribute__((__packed__)) object { ... };
for packing (GCC).