j.j.fishbat@[EMAIL PROTECTED]
wrote:
> Hi all
>
> I have a program which, with inessential details removed,
> looks like this:
>
> --
> #include <stdlib.h>
> #include <stdio.h>
>
> static int punme(void** dat,size_t newsize)
> {
> void *newdat = realloc(*dat,newsize);
>
> if (! newdat) return 1;
>
> *dat = newdat;
>
> return 0;
> }
>
> int main (void)
> {
> char *dat = malloc(30);
>
> int ret = punme((void**)&dat,40);
>
> printf("punme returns %i\n",ret);
>
> return 0;
> }
> --
>
> My compiler (gcc -Wall -O3) tells me that "typepun.c:19:
> warning: dereferencing type-punned pointer will break
> strict-aliasing rules". The code works as expected, ie,
> prints that punme returns 0.
>
> Who is the idiot? Me or the compiler?
> ...
You perform memory reinterpretation in your code. You have an lvalue
'dat' of type 'char*', which is reinterpreted as an lvalue of type
'void*' by using a conversion followed by a dereference '*(void**)
&dat'. In general, accessing the lvalue obtained by such
reinterpretation causes undefined behavior in C, unless the types are
"similar enough". In strict-aliasing mode (implied by -O3) GCC assumes
that such reinterpretations are not performed in the code. This is why
it issues the warning.
--
Best regards,
Andrey Tarasevich


|