This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Strict aliasing and allocation functions
- From: Carsten Steger <stegerc at informatik dot tu-muenchen dot de>
- To: gcc-help at gcc dot gnu dot org
- Date: Thu, 8 Apr 2004 15:47:34 +0200 (CEST)
- Subject: Strict aliasing and allocation functions
We have a lot of code lying around where memory allocation is
encapsulated in functions that return error values as ints and
return the allocated memory through a void **. A little example
that shows the gist of the code is as follows:
#include <stdlib.h>
#include <stdio.h>
int alloc(size_t n, void **p)
{
void *a;
a = malloc(n);
*p = a;
return a == NULL;
}
int main(void)
{
int *a, res;
res = alloc(10,(void **)&a);
free(a);
return 0;
}
Unfortunately, from gcc 3.3 onwards, this code generates the
following warning:
gcc -O3 -Wall -o alloc alloc.c
alloc.c: In function `main':
alloc.c:18: warning: dereferencing type-punned pointer will break
strict-aliasing rules
Is there any way to prevent the warning without major changes to
the code (i.e., without substantial changes to the signature of
alloc)? In other words, is there a way to tell gcc to treat
the returned pointer p in the same manner as the pointer a
returned by malloc, for which no type-punning warning is
generated?
Cheers, Carsten