The name pretty much says it all. Can someone direct me or provide me with code that will reliably trigger alias errors with several recent gcc versions? The reason I ask is because I'm trying to learn the effects of a strict alias, but no matter how hard I try to break it, gcc always comes up with the “right” result, doing some kind of test on how to deal with situations where you want to break the rules are pretty much worthless. I'm not asking for warnings (-Wstrict-aliasing = 2 gives warnings in almost everything I do), but code that actually doesn't work when optimizing with -fstrict-aliasing.
#include <stdio.h>
#include <stdint.h>
typedef struct mystruct_s {
uint32_t int1;
uint32_t int2;
} mystruct_t;
typedef mystruct_t __attribute__( ( may_alias ) ) mystruct_alias_bad1_t;
typedef struct mystruct_alias_s {
uint32_t int1;
uint32_t int2;
} __attribute__( ( may_alias ) ) mystruct_alias_t;
static __attribute__( ( optimize( "no-strict-aliasing" ) ) ) void myfunc1_alias1( void ) {
uint32_t var, *i = &var;
float *f = (float*)&var;
*i = 100;
printf( "[test-5] %u", var );
*f = 0.f;
printf( " %u (%s)\n", var, var != 100 ? "OK" : "FAIL" );
}
#pragma GCC optimize "no-strict-aliasing"
static void myfunc1_alias2( void ) {
uint32_t var, *i = &var;
float *f = (float*)&var;
*i = 100;
printf( "[test-6] %u", var );
*f = 0.f;
printf( " %u (%s)\n", var, var != 100 ? "OK" : "FAIL" );
}
#pragma GCC optimize "strict-aliasing"
static void myfunc1( void ) {
uint32_t var, *i = &var;
float *f = (float*)&var;
*i = 100;
printf( "[test-7] %u", var );
*f = 0.f;
printf( " %u (%s)\n", var, var != 100 ? "OK" : "FAIL" );
}
int main( int argc, char **argv ) {
unsigned char buf[sizeof( mystruct_t )] = { 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02 };
printf( "[test-1] int2 == %08X\n",
( (mystruct_t*)buf )->int2
);
printf( "[test-2] int1 == %08X, int2 == %08X\n",
*(uint32_t*)buf,
( (uint32_t*)buf )[1]
);
printf( "[test-3] int1 == %08X, int2 == %08X\n",
( ( __attribute__( ( may_alias ) ) mystruct_t*)buf )->int1,
( (mystruct_alias_t*)buf )->int2
);
printf( "[test-4] int1 == %08X, int2 == %08X\n",
( ( __attribute__( ( may_alias ) ) mystruct_t* [1] ) { (mystruct_t*)buf } )[0]->int1,
( ( mystruct_t* [1] ) { (mystruct_t*)buf } )[0]->int2
);
myfunc1_alias1();
myfunc1_alias2();
myfunc1();
return 0;
}
Final editing:
, mnunberg :
__attribute__( ( may_alias ) )
, (, , ) - .
__attribute__( ( optimize( "no-strict-aliasing" ) ) )
, . .
#pragma GCC optimize "no-strict-aliasing"
, , , ().