以下代码在使用 gcc 4.1 版和 -O2 标志编译时会出错。它可以与 gcc 版本 4.4、4.5 等一起编译。
错误是:
warning: dereferencing type-punned pointer will break strict-aliasing rules
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));
}
}