Memory alignment check

前端 未结 3 1112
闹比i
闹比i 2021-02-01 21:34

I want to check whether an allocated memory is aligned or not. I am using _aligned_malloc(size, align); And it returns a pointer. Can I check it by simply dividing

3条回答
  •  长发绾君心
    2021-02-01 21:51

    On a modern Unix system a pointer returned by malloc is most likely 16 byte aligned as this is required for things like SSE. To check for alignment of a power of 2 you can use:

    ((unsigned long)p & (ALIGN - 1)) == 0
    

    This is simply a faster version of (p % ALIGN) == 0. (If ALIGN is a constant your compiler will probably automatically use the faster version above.)

提交回复
热议问题