This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: strict aliasing: how to swap pointers
- From: Andrew Haley <aph at redhat dot com>
- To: Evan Jones <evanj at MIT dot EDU>
- Cc: John Love-Jensen <eljay at adobe dot com>, GCC-help <gcc-help at gcc dot gnu dot org>
- Date: Wed, 30 Apr 2008 15:49:16 +0100
- Subject: Re: strict aliasing: how to swap pointers
- References: <C43DE145.2F8A9%eljay@adobe.com> <4818849D.6060701@mit.edu>
Evan Jones wrote:
> John Love-Jensen wrote:
>> void** is not void*.
>
> Ah, of course. So with strict aliasing, GCC assumes that a void**
> pointer only points to variables of exactly type void*? This would
> explain my confusion. I was assuming that since T* is convertible to
> void*, void** can point to any T*. It makes sense that this is not true.
>
> I wish I could get GCC to generate a "surprising" optimization for a
> void**/T** type pun, but I have been unable to do so. This, of course,
> doesn't mean that ignoring the warning is safe.
>
> It seems to me that the lesson for me is that when doing low-level
> type-unsafe manipulation, void* pointers should be used. Since GCC must
> assume that void* pointers can point anywhere, it will not be able to
> optimize away the accesses to them, which is what I want in this case.
> Please correct me if I am wrong about this.
gcc will look through temporaries of type void* if the information is
visible. So, trying to defeat the type system by using void* variable as
temporaries doesnt work because gcc will simply delete any pointless
temporaries.
so, this:
int *sp = &int_var;
void *vp = sp;
*(short*)vp = 22;
is undefined behaviour, and may well not do what you want.
Andrew.