I have a statically allocated array of chars. Can I reuse this array for storing different types without violating strict aliasing rule? I don't understand strict aliasing really well, but here's an example of a code that does what I want to do:
#include <stdio.h>
static char memory_pool[256 * 1024];
struct m1
{
int f1;
int f2;
};
struct m2
{
long f1;
long f2;
};
struct m3
{
float f1;
float f2;
float f3;
};
int main()
{
void *at;
struct m1 *m1;
struct m2 *m2;
struct m3 *m3;
at = &memory_pool[0];
m1 = (struct m1 *)at;
m1->f1 = 10;
m1->f2 = 20;
printf("m1->f1 = %d, m1->f2 = %d;\n", m1->f1, m1->f2);
m2 = (struct m2 *)at;
m2->f1 = 30L;
m2->f2 = 40L;
printf("m2->f1 = %ld, m2->f2 = %ld;\n", m2->f1, m2->f2);
m3 = (struct m3 *)at;
m3->f1 = 5.0;
m3->f2 = 6.0;
m3->f3 = 7.0;
printf("m3->f1 = %f, m3->f2 = %f, m3->f3 = %f;\n", m3->f1, m3->f2, m3->f3);
return 0;
}
I've compiled this code using gcc with -Wstrict-aliasing=3 -fstrict-aliasing, and it works as intended:
m1->f1 = 10, m1->f2 = 20;
m2->f1 = 30, m2->f2 = 40;
m3->f1 = 5.000000, m3->f2 = 6.000000, m3->f3 = 7.000000;
Is that code safe? Assume memory_pool is always large enough.