gpt4 book ai didi

c++ - 警告 : dereferencing type-punned pointer will break strict-aliasing rules (even for void pointers)

转载 作者:行者123 更新时间:2023-11-30 01:58:14 62 4
gpt4 key购买 nike

<分区>

以下代码在使用 gcc 4.1 版和 -O2 标志编译时会出错。它可以在 gcc 4.4、4.5 等版本中正常编译。

错误是: 警告:取消引用类型双关指针将打破严格的别名规则

void foo(void **a = NULL);

int main()
{
int *a;
foo((void **)&a); //I get above error here

cout << "a[0] " << *a << endl;
cout << "a[1] " << *(a+1) << endl;
cout << "a[2] " << *(a+2) << endl;
return 0;
}

void foo(void **a)
{
int b[3];
b[0] = 10; b[1] = 20; b[2] = 35;
if(a != NULL) {
*a = (char *)malloc(20);
memcpy((char *)(*a), &b, 12);
}

}

现在为了避免这种情况,我可以像下面给出的那样编程。这是避免此警告的好解决方案吗?我能够在此代码中避免此警告。

void foo2(char **a = NULL);

int main()
{
char *a;
float c[3];
foo2(&a);
memcpy(&c, a, sizeof(c));
cout << "c[0] " << *c << endl;
cout << "c[1] " << *(c+1) << endl;
cout << "c[2] " << *(c+2) << endl;
return 0;
}

void foo2(char **a)
{
float c[3];
c[0] = 10.123; c[1] = 2.3450; c[2] = 435.676;
if(a != NULL) {
*a = (char *)malloc(sizeof(c));
memcpy((char *)(*a), &c, sizeof(c));
}
}

62 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com