Question

Considering this code, VC9 doesn't detect aliasing :

typedef struct { int x, y; } vec_t;

void rotate_cw(vec_t const *from,
               vec_t       *to)
{
        /* Notice x depends on y and vice versa */
        to->x = from->y;
        to->y = -from->x;
}

/* ... */
vec_t a, b;
rotate_cw(&a, &b); /* OK, no aliasing */
rotate_cw(&a, &a); /* FAIL, aliasing is not detected */

The obvious fix is to use a temporary :

void rotate_cw(vec_t const *from,
               vec_t       *to)
{
        int temp = from->x;
        to->x = from->y;
        to->y = -temp;
}

Is this standard behavior ? I was expecting that the compiler, unless told so, would assume both pointers to be possibly aliased.

Was it helpful?

Solution

Check out this answer.

Try putting __restrict before the parameters, seems to be the only way anybody found of getting MSVC to give any warnings.

OTHER TIPS

The code as written is perfectly valid, in C89 or C99. It is obscure, but there is nothing for the compiler to diagnose, so it doesn't diagnose.

If you used C99 and 'restrict' on both parameters of the function, then you would get an error - if your compiler supports C99. AFAIK, no current version of MSVC yet supports C99 fully.

Before C99 invented the restrict qualifier, some C compilers included optimization options which would direct them to make certain assumptions about pointer usage; the manuals I've seen for such compilers expressly warned that such optimizations were not standards-compliant, and may arbitrarily cause code using certain particular constructs whose behavior was defined by the Standard to behave in a manner which was contrary to both the Standard and programmer intention. From the point of view of the manual, the optimizations told the compiler to compile a subset of C which did not define the behavior of certain corner cases that were defined in C, but which would allow the generation of more efficient code for those cases it did define.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top