A different, and possibly more realistic example. Perhaps this avoids alignment issues.
O_o
The example may avoid alignment issues, but the example still has "out-of-bounds" access.
The compiler doesn't "see" a `foo' structure having two integers; the compiler "sees" a `foo2' structure which has three integers; the compiler copies three integers.
As before, the situation you ask about isn't a "different types" situation as far as the compiler is concerned. Yes. The types are actually different, but you told the compiler that the types are the same, and so the compiler does exactly what it would do if the types actually were the same.
[Edit]
I think I possible see the problem.
Code:
printf("a = %d b = %d\n", bar2.a, bar2.b);
The use of `bar2' after being assigned is irrelevant.
Code:
bar2 = *((struct foo *)&bar);
The use of `bar' is relevant. The compiler assigns a value to `bar2.extra' because it is used with the assignment line. The "out-of-bounds" access happens because the compiler assigns `bar2.extra' from `((struct foo *)&bar)->extra' which does not exist.
[/Edit]
Soma
Code:
#include <stdio.h>
struct foo {
int a;
int b;
};
struct foo2 {
struct foo link;
int extra;
};
void Dump(struct foo2 * bar2){printf("a = %d b = %d extra = %d\n", bar2->link.a, bar2->link.b, bar2->extra);}
int main(void)
{
struct foo2 bar2;
int maybe[1] = {44};
{
struct foo bar = { .a = 42, .b = 43 };
Dump((struct foo2 *)&bar);
/* bar2->extra is set according to what memory */
bar.a = 46; /* maybe */
}
{
int bar[2] = {44, 45};
Dump((struct foo2 *)&bar);
/* bar2->extra is set according to what memory */
}
return 0;
}