I was wondering, is casting to and from a pointer to an incomplete type undefined behavior?
struct _obj;
typedef _obj obj;
typedef struct{
int val;
} obj_int;
void print_stuff(obj* o){
printf("%d\n", ((*obj_int)(o)) -> val);
}
Usually.
Standard 6.3.2.3/7:
A pointer to an object or incomplete type may be converted to a pointer to a different object or incomplete type. If the resulting pointer is not correctly aligned for the pointed-to type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer. When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.
So if o
points at any struct object whose first member is an int
, you're fine. If it points at the beginning of memory obtained from malloc
, where the representation of an int
has been written, you're fine. But if it points at a char[sizeof(int)]
or some such thing, you might have alignment issues.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With