On Tue, 06 May 2008 09:43:53 -0700, vippstar wrote:
> On May 6, 6:46 pm, j.j.fish...@[EMAIL PROTECTED]
wrote:
>> #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;}
Heh, this looks familiar. :)
>> 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 (cast) and assign a char ** to a void **. void ** is not like void
> *.
> Fixed your code:
>> static int punme(void* dat,size_t newsize) { void **tmp = dat;
>> void *newdat = realloc(*tmp, newsize);
This doesn't fix the problem. This merely reorganises the code in a form
that the compiler may happen to not warn about.
The problem is that dat is defined as char *. You can't pretend it's
defined as a void *. The language doesn't let you. A fixed version looks
like
#include <stdlib.h>
#include <stdio.h>
static void *punme(void *dat, size_t newsize) {
return realloc(dat, newsize);
}
int main (void)
{
char *dat = malloc(30);
char *newdat = punme(dat, 40); /* or call realloc directly */
if (newdat != NULL) dat = newdat;
printf("punme would have returned %d\n", (newdat == NULL ? 1 : 0));
return 0;
}


|