Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is This "Type Punning" Well-Defined?

Tags:

c

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);
}
like image 241
Shokwav Avatar asked Mar 23 '23 15:03

Shokwav


1 Answers

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.

like image 86
aschepler Avatar answered Mar 29 '23 09:03

aschepler