当一个结构具有非常量成员而另一个具有常量成员时,从一种结构转换为另一种结构(两者具有相同的形状)是否安全?该代码演示了我正在尝试做的事情..
#include <stdio.h>
#include <stdlib.h>
struct nonConst {
int value;
struct nonConst * next;
};
struct Const {
const int value;
struct nonConst * const next;
};
int main (int argc, char ** argv) {
struct nonConst * nc = (struct nonConst*)malloc(sizeof(struct nonConst));
nc->next = NULL;
nc->value = 8888;
struct Const * c = (struct Const*)nc;/*cast the non-const members to const members*/
fprintf(stdout, "%d\n", c->value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上述安全(或在某些情况下安全)还是我会遇到问题?
这属于标准未明确涵盖的领域。首先,没有类型的内存由 分配malloc。
写入动态分配的空间会设置内存的有效类型。但该标准没有说明是否nc->value“印记”整个struct nonConst. 或仅写入int. 同样,它没有说明是否fprintf(stdout, "%d\n", c->value);需要存在整个有效struct Const内容,或者是否只读取const int.
这种区别很重要,因为可以从同一内存位置写入int和读取 a (严格的别名规则特别提到了这一点)。const int
一些主要编译器采取的立场是nc->value印记c->value/需要整个结构,而不仅仅是涉及的成员。因此,实际上,我认为使用这段代码并不安全。
我将在本答案的第二部分详细介绍该主题。