Memory alignment check

前端 未结 3 1108
闹比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:57

    An "aligned" pointer by definition means that the numeric value of the pointer is evenly divisible by N (where N is the desired alignment). To check this, cast the pointer to an integer of suitable size, take the modulus N, and check whether the result is zero. In code:

    bool is_aligned(void *p, int N)
    {
        return (int)p % N == 0;
    }
    

    If you want to check the pointer value by hand, just look at the hex representation of the pointer and see whether it ends with the required number of 0 bits. A 16 byte aligned pointer value will always end in four zero bits, for example.

提交回复
热议问题