J. Doe J. Doe - 3 months ago 13
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
undef_t
pointers in the program are casted
other_t
pointers and assume further that all procedures which take
undef_t*
cast them to
other_t*
before use.

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

Answer

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 6.3.2.3 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.

Comments