BIC-MNI / libminc

libminc is the core library and API of the MINC toolkit
Other
19 stars 29 forks source link

Invalid casting in input_nifti.c and input_mgh.c #53

Closed seanm closed 9 years ago

seanm commented 9 years ago

These 2 files have many warnings of the form:

/libminc/volume_io/Volumes/input_nifti.c:88:25: warning: cast from 'char *' to 'short *' increases required alignment from 1 to 2 [-Wcast-align]
        tmp = (double) ((short *)data)[j];
                        ^~~~~~~~~~~~~

Note that 'data' is defined as:

  char data[CHUNK_SIZE];

Which means it may be aligned as char (1 byte).

This is not just pedantic, but a real bug that will expose itself on some architectures (I think ex: ARM) where unaligned access is not allowed. i.e. short* must be aligned in memory on the size of short (2 bytes).

One fix would be to use memcpy like:

    short temp;
    memcpy(&temp, (data + j*sizeof(short)), sizeof(short));  
    tmp = (double)temp;

Another might be to allocate 'data' with malloc() so that at least it's guaranteed to be aligned suitably for anything from char* to double*. This will fix the bug at runtime, but probably not get rid of the warning.

Other ideas?

seanm commented 9 years ago

That satisfied the complier anyway, and looks correct AFAICT.

There are similar shenanigans in m2util.c, if you care to take a stab:

/libminc/libsrc2/m2util.c:786:17: warning: cast from 'unsigned char *' to 'int *' increases required alignment from 1 to 4 [-Wcast-align]
          t = * ( int * ) src_ptr;
                ^~~~~~~~~~~~~~~~~