我似乎错过了关于有效类型的几个难题......代码中的注释基本上是我的问题,但这是我能想到用适当方式提出这个问题的唯一方法上下文。困惑于有效的类型规则
#include <stdlib.h>
#include <string.h>
typedef struct foo {
int n;
} Foo;
int main(void)
{
// No effective type yet because there has been no write to the memory.
Foo *f = malloc(sizeof(Foo));
// Effective type of `f` is now `Foo *`, except I'm writing to
// `f->n`, so shouldn't it be `int *`? Not sure what's going on here.
f->n = 1;
// No effective type yet because there has been no write to the memory.
char *buf = malloc(sizeof(Foo));
// Effective type of `buf` is `Foo *`, despite it being declared as
// `char *`.
// It's not safe to modify `buf` as a `char` array since the effective type
// is not `char`, or am I missing something?
memcpy(buf, f, sizeof(Foo));
// The cast here is well defined because effective type of `buf` is
// `Foo *` anyway, right?
((Foo *)buf)->n++;
// I'm not even sure this is OK. The effective type of `buf` is `Foo *`,
// right? Why wouldn't it be OK then?
memcpy(f, buf, sizeof(Foo));
// Safe if the last `memcpy` was safe.
f->n++;
// buf now points to invalid memory.
free(buf);
// Pointers with different declared types point to the same object,
// but they have the same effective type that is not qualified by
// `restrict`, so this doesn't violate strict aliasing, right?
// This is allowed because `f` was allocated via `malloc`,
// meaning it is suitably aligned for any data type, so
// the effective type rules aren't violated either.
buf = (void *)f;
// `f`, and consequently `buf` since it points to the same object as `f`,
// now point to invalid memory.
free(f);
}
我是否正确认为所有这些都是好的,或者我在某些情况下是错的?我意识到这是边界问多个问题,但我基本上是问我对有效类型和严格别名的理解是否正确。 GCC没有产生诊断我-pedantic-errors -Wextra -Wall -O2 -fstrict-aliasing -Wstrict-aliasing
'BUF =(无效*)F'始终是有效的(无论F'的'的类型),仅仅是因为严格的别名规则有一个例外,它允许一个'字符*'别名的任何其它类型。 – user3386109