How to allocate memory with alignment of 16 bytes?

I use Marshal.GlobalHAlloc to allocate memory. As the documentation says: "This method provides the Win32 LocalAlloc function from Kernel32.dll.". GlobalAlloc documentation says it will be aligned by 8 bytes, but LocalAlloc says nothing about alignment.

For example, I want to allocate 1024 bytes and make sure that it is aligned to 16. Will it work when I allocate 1024 + 16 bytes, then I check the% 16 pointer? If the result is 0, it means the memory is aligned when it is not equal to 0, I just increase the pointer to fit my expectations. The problem is that I don’t know if I aligned the pointer, is it really aligned in physical memory?

+7
source share
1 answer

All Windows heap allocators are aligned to 8. You can fix this by overshooting and setting the pointer, for example:

  var rawptr = Marshal.AllocHGlobal(size + 8); var aligned = new IntPtr(16 * (((long)rawptr + 15) / 16)); // Use aligned //... Marshal.FreeHGlobal(rawptr); 
+10
source

All Articles