J. Doe J. Doe - 1 year ago 66
C Question

Does casting a T pointer to a T' pointer and back yield the original pointer if T' is an incomplete type?

Consider the following snippet which is adapted from the Tor source code:

/* This can be a malloc wrapper with minimal initialization. */
other_t *make_other(void);

/* This struct is never defined. */
struct undef;
typedef struct undef undef_t;

undef_t *make_undef(void)
other_t *other = make_other();
return (undef_t*)other;

Assume that all
pointers in the program are casted
pointers and assume further that all procedures which take
cast them to
before use.

According to section of the C99 standard, the cast within the
statement invokes undefined behavior if
is not correctly aligned as a pointer to
, but if it is, casting the result of
back to
yields the original pointer as returned by
. However,
is an undefined type, and I cannot find any alignment rules regarding these. Do these conversions still work like they would if
was defined and had the right alignment?

Answer Source

Since it isn't specified that the type must not be incomplete, the rule1 simply applies to all types, complete or not.

Additionaly all pointers to structs are guaranteed to have the same alignment requirements2.

Therefore if the pointer is correctly aligned, the conversion to undef_t and back to other_t is defined.

This is actually being done all the time. The type void is an incomplete type, and conversion to, and from it, is defined.

1 (Quoted from: ISO:IEC 9899:201X Pointers 7)
A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned 68) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

2 (Quoted from: ISO:IEC 9899:201X 6.2.5 Types 28)
All pointers to structure types shall have the same representation and alignment requirements as each other.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download