[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <5524ADB9.9050409@openwall.com>
Date: Wed, 08 Apr 2015 07:25:29 +0300
From: Alexander Cherepanov <ch3root@...nwall.com>
To: discussions@...sword-hashing.net
Subject: Re: [PHC] On type aliasing and similar issues
On 2015-04-08 06:03, Samuel Neves wrote:
> On 04/08/2015 03:37 AM, Alexander Cherepanov wrote:
>> AFACT this is implementation-defined in C89 (3.3.2.3) and fully defined in C99 and C11 (6.5.2.3p3).
>
> Yes, type punning with unions is now OK (though implementation-defined; accessing the wrong member may still trap) in
uint32_t[2] and uint64_t don't have padding bits and have the same size
so this particular example is fully defined.
> C99 and above. What is being dereferenced in the example is the pointer to the union, not the members, so I'm not sure
> strict aliasing's undefined behavior applies. The example could be further improved to demonstrate this:
>
> #include <stdint.h>
> #include <stdio.h>
>
> union U {
> uint32_t x[2];
> uint64_t y;
> };
>
> extern union U * v;
>
> void f() {
> uint32_t * p = &v->x[0];
> uint64_t * q = &v->y;
> *p = 17;
> *q = 42;
> printf("%u\n", v->x[0]);
> }
>
> While Clang and recent GCC do what one would hope (print 42), GCC 3.4 and Intel compiler print 17.
Yes, it seems the standard intends to permit access to wrong members
only via . and -> operators. You cannot access them in a less direct
way. If you pass them to another function then recent gcc -O2 will print
17 too.
#include <stdint.h>
#include <stdio.h>
union U {
uint32_t x[2];
uint64_t y;
} v;
uint32_t f(uint32_t *a, uint64_t *b)
{
*a = 17;
*b = 42;
return *a;
}
int main()
{
printf("%u\n", (unsigned)f(&v.x[0], &v.y));
return 0;
}
--
Alexander Cherepanov
Powered by blists - more mailing lists