Following code gives error when compiled with gcc version 4.1 and with -O2 flag. It compiles fine with gcc version 4.4, 4.5 etc.
The error is:
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);
}
}
Now to avoid this can I program like given below. Is this is good solution to avoid this warning? I am able to avoid this warning in this code.
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));
}
}