Search code examples
calignmentfftwstrict-aliasing

Strict aliasing violation in C


Does the following violate strict aliasing rule in C?

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int ialignment_of(double *p)
{
     return (int)(((uintptr_t) p) % 16);
}


int main(void)
{
    double _Complex * a = malloc(16*sizeof ( *a));

    int alen = ialignment_of((void*)a);

    for (int i = 1; i < 8; ++i)
    {
        if ( ialignment_of((void*)(a+i)) == alen)
        {
            printf("pass\n");
            break;
        }
    }
    free(a);
}

I think it is violated but I am confused as FFTW library say that we can do this. This function is defined in kernel/align.c for a real floating pointer. But in the fftw documentation, it is written that we can cast pointer (for example here from double complex to double)

Two arrays have equivalent alignment (for the purposes of applying a plan) if and only if fftw_alignment_of returns the same value for the corresponding pointers to their data (typecast to double* if necessary).


Solution

  • Strict aliasing violations only happen when an object of a certain effective type is reinterpreted as an invalid type through lvalue access. The code you posted contains no lvalue access so there can be no strict aliasing violations.

    Furthermore, a chunk of data returned from malloc has no effective type until write-accessed, so there can be no strict aliasing violation for that reason as well.

    (uintptr_t) p grabs the address and converts it to an integer type. It doesn't access the actual object. Less sloppy code would be written with const correctness, but the code is otherwise OK.