Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory alignment check

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 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?

like image 801
delete_this_account Avatar asked Jun 05 '11 00:06

delete_this_account


People also ask

What is meant by memory alignment?

Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory. First we must conceptualize main memory as a contiguous block of consecutive memory locations. Each location contains a fixed number of bits.

What is the purpose of memory alignment?

The CPU can operate on an aligned word of memory atomically, meaning that no other instruction can interrupt that operation. This is critical to the correct operation of many lock-free data structures and other concurrency paradigms.

What is 32bit alignment?

For instance, in a 32-bit architecture, the data may be aligned if the data is stored in four consecutive bytes and the first byte lies on a 4-byte boundary. Data alignment is the aligning of elements according to their natural alignment.

How do I know if my address is 4k aligned?

4k memory segments start at a hex address ending with 000. So all the addresses that end with 000 start on a 4 k boundary. However, addresses that end with 0000, 2000, 4000, 6000, 8000, a000, c000, or e000 also start on an 8k boundary. This is because hex 1000 is 4k or 2^12.


2 Answers

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.

like image 99
Greg Hewgill Avatar answered Sep 25 '22 05:09

Greg Hewgill


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

like image 42
nominolo Avatar answered Sep 25 '22 05:09

nominolo