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