开发者

Memory alignment check

I want to check whether an allocated m开发者_开发知识库emory is aligned or not. I am using _aligned_malloc(size, align); And it returns a pointer. Can I check it by simply dividing the pointer content by 16 for example? If the the pointer content is divisible by 16, does it mean that the memory is aligned by 16 bytes?


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.


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.)


Memory returned by malloc is aligned for everything (ie, it generally uses the an alignment that works for everything)*. That means, if you have an alignment issue, it is something else.

http://www.delorie.com/gnu/docs/glibc/libc_31.html

http://msdn.microsoft.com/en-us/library/ms859665.aspx

(There appears to be exceptions for higher orders of alignment, which is an unusual requirement anyway.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜