Strict aliasing and allocation functions

Carsten Steger stegerc@informatik.tu-muenchen.de
Thu Apr 8 13:47:00 GMT 2004


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



More information about the Gcc-help mailing list