[Debburn-devel] Re: [PATCH] fixes for aliasing bugs

neologix at free.fr neologix at free.fr
Thu Sep 28 04:44:20 UTC 2006


>Hi again,
>
>Lorenz Minder wrote:
>> chains do not solve aliasing issues. (However, the fact that the old
>> writing was very obfuscated suggests that maybe the obvious solution
>> does not work on some old / weird compiler; some checking might be in
>> order.)
>
>Ok, I had some second thoughts on that: It is not strict ANSI C to do
>pointer arithmetic on void *, so the fix is not correct either. I think
>we have to make buffer a char *. I'll investigate this further and come
>up with an updated patch.>
>
>Best,
>--Lorenz


It's not just "not strict ANSI C", it's just false.
When performing arithmetic on pointers, the compiler _needs_ the type of the
pointed to objects to do the calculations (it multiplies the offest by the
object's size). When dealing with void pointers, it has no way to know the
actual size, so it can't do anything with it.


http://c-faq.com/ansi/voidparith.html


********************************************

int main() {
        int a = 1;

        *((short *)(void *) &a) += 1;

        printf("%d\n", a);

        return a;
}

~$ /usr/local/gcc4/bin/gcc -O3 test.c
~$ ./a.out
1

********************************************

This code is weird.
If you omit the (void *) cast, gcc will warn you:

test.c:6: warning: dereferencing type-punned pointer will break strict-aliasing
rules


When using -O2 optimization or above, gcc enforces this "strict aliasing" rule,
and therefore doesn't even bother to do the calculation.
Moreover, there is great danger when playing loose with pointers, "unaligned
access". You can end up asking the processor to fetch a value at a location he
doesn't like (in this case, it is unlikely because if the adress is aligned for
an int, it is probably for a short).

http://www.cellperformance.com/mike_acton/2006/06/understanding_strict_aliasing.html







More information about the Debburn-devel mailing list