is this a valid approach to aliasing?

Andrew Haley aph@redhat.com
Tue Feb 12 09:43:00 GMT 2008


Robert William Fuller wrote:
>
> Naturally, when I started trying to call this function, I started 
> getting the type-punned pointer aliasing warnings.  The code in question 
> looked roughly like this:
> 
> static opt_param_t *shrtOpts, *longOpts;
> 
> rc = reallocItems((void **) &shrtOpts, sizeof(opt_param_t), 
> &shrtOptAlloc, numShrtOpts, newShrtOpts, shrtOptHint);
> 
> Obviously, this breaks the aliasing rules.  I read that I could work 
> around this by casting through a union.  I settled on this approach, but 
> I'm not sure if it is valid, or if I'm merely masking the problem:
> 
> typedef union _opt_param_alias_t {
> 
>     opt_param_t *o;
>     void *v;
> 
> } opt_param_alias_t;
> 
> rc = reallocItems(&((opt_param_alias_t *) &shrtOpts)->v, 
> sizeof(opt_param_t), &shrtOptAlloc, numShrtOpts, newShrtOpts, shrtOptHint)

It really isn't necessary to do this.  The rule is that you mustn't use
a pointer cast to create an lvalue of incompatible type.  So, do this:

static opt_param_t *shrtOpts, *longOpts;

void *p1;

rc = reallocItems(&p1, sizeof(opt_param_t),
    &shrtOptAlloc, numShrtOpts, newShrtOpts, shrtOptHint);
shrtOpts = p1;

Andrew.




More information about the Gcc-help mailing list