转换不完整的结构指针是未定义的行为吗?

Is casting incomplete struct pointers undefined behavior?

我目前正在阅读一些严格的别名规则,我想知道将指针强制转换为不完整的结构是否是未定义的行为。

示例 1:

#include <stdlib.h>

struct abc;

int main(int argc, char *argv[])
{
  struct abc *mystruct;
  char *buf;

  buf = malloc(100);
  mystruct = (struct abc*)buf;

  // and then mystruct could be submitted to a function, where it is
  // casted back to a "char *", the "struct abc" will never be completed.

  return 0;
}

示例 2:

struct abc1;
struct abc2;

int foo(struct abc1 *mystruct1)
{
  struct abc2 *mystruct2;

  mystruct2 = (struct abc2 *)mystruct1;

  // and then mystruct2 could be submitted to a function, where it is
  // casted to a "char *", both structs stay incomplete.

  return 0;
}

所以,我的问题是:是否像 c11 标准所禁止的那两个示例中那样将指针强制转换为不完整的结构?如果是,标准的哪一部分禁止这样做?

标准的一个关键相关部分是 C11 §6.2.5 Types ¶28:

28 A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

48) The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions.

另一个是§6.3 Conversions and particularly §6.3.2.3 Pointers ¶7:

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 aligned68) for the referenced 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.

68) In general, the concept ''correctly aligned'' is transitive: if a pointer to type A is correctly aligned for a pointer to type B, which in turn is correctly aligned for a pointer to type C, then a pointer to type A is correctly aligned for a pointer to type C.

因此,我的理解是问题中显示的任何一个示例代码片段都没有问题。结构类型不完整,但这对于显示的操作来说不是问题。代码的 'and then' 部分不必有问题 — 这取决于实际存在的内容。