a puzzle of struct in gcc (4.6.0 20110212).

Axel Freyn axel-freyn@gmx.de
Tue Feb 22 14:31:00 GMT 2011


Hi
On Tue, Feb 22, 2011 at 12:15:12PM +0800, yansheng si wrote:
> Hi,
> I build following code in gcc(4.6.0 20110212), the result of print is:
>   temp1 = 0x11111111
>   temp2 = 0x11111111
>   temp3 = 0x22222211
> 
> howerer, in gcc(Ubuntu 4.4.3-4ubuntu5), the result of print is:
>   temp1 = 0x22111111
>   temp2 = 0x22221111
>   temp3 = 0x22222211
> 
>  Why temp1 equal to temp2 in gcc 4.6, but not in gcc 4.4?
> 
> Thanks
> 
> ////////////////////////////////////////////////////////
> //test code
> ////////////////////////////////////////////////////////
> #include <stdio.h>
> 
> int main(int argc, char* argv[])
> {
> 	struct {
> 		int u1;
> 		int u2[2];
> 	} date1 = {0x00000000, {0x11111111, 0x22222222}};
> 	struct {
> 		int u1;
> 		int u2;
> 		int u3;
> 	} date2 = {0x00000000, 0x11111111, 0x22222222};
> 	int temp1 = *(int*)((char*)(&date1.u2)+1);
> 	printf("temp1 = 0x%x\n", temp1);
> 	int temp2 = *(int*)((char*)(&date1.u2)+2);
> 	printf("temp2 = 0x%x\n", temp2);
> 	int temp3 = *(int*)((char*)(&date2.u2)+3);
> 	printf("temp3 = 0x%x\n", temp3);
> 	return 0;
> }

I think your code results in undefined behaviour: You convert a "pointer
to int" to a "pointer to char" -- that's fine. But then you add 1,2 or 3
and convert this pointer back to "pointer to int". Now, this new pointer
is NOT correctly aligned for integers. And the C-standard says "A pointer
to an object or incomplete type may be converted to a pointer to a
different object or incomplete type. If the resulting pointer is not
correctly aligned57) for the pointed-to type, the behavior is
undefined."

So I think it's simply random. In addition, when you change the compile
parameters (e.g. optimizing with -O, -O2 or -O3) this might also change
your results...

HTH,

Axel



More information about the Gcc-help mailing list