Mis-aligned pointers on x86

后端 未结 8 632
一整个雨季
一整个雨季 2020-11-30 06:36

Can someone provide an example were casting a pointer from one type to another fails due to mis-alignment?

In the comments to this answer, bothie states that doing s

相关标签:
8条回答
  • 2020-11-30 07:33

    To enjoy the exception, call SetErrorMode with SEM_NOALIGNMENTFAULTEXCEPT:

    int main(int argc, char* argv[])
    {
       SetErrorMode(GetErrorMode() | SEM_NOALIGNMENTFAULTEXCEPT);
       ...
    }
    

    See Windows Data Alignment on IPF, x86, and x64 for details.

    0 讨论(0)
  • 2020-11-30 07:37

    gcc when auto-vectorizing assumes that uint16_t* is aligned to a 2-byte boundary. If you violate this assumption, you can get a segfault: Why does unaligned access to mmap'ed memory sometimes segfault on AMD64?

    So respecting C alignment rules matters even when targeting x86.


    Use this to efficiently express an unaligned load in C:

    static inline
    uint32_t load32(char *p)     // char*  is allowed to alias anything
        uint32_t tmp;
        memcpy(&tmp, p, sizeof(tmp));
        return tmp;
    }
    

    On x86 it will compile to the single mov you expect (or auto-vectorize or whatever), but on SPARC or MIPS before MIPS64r6 or whatever it will compile to whatever instruction sequence is necessary for an unaligned load. This use of memcpy will optimize away entirely on targets that support unaligned loads.

    i.e. your compiler knows whether the target ISA supports unaligned loads or not, and will emit asm that does them or not as it sees fit.

    0 讨论(0)
提交回复
热议问题