我似乎錯過了關於有效類型的幾個難題......代碼中的註釋基本上是我的問題,但這是我能想到用適當方式提出這個問題的唯一方法上下文。困惑於有效的類型規則
#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