zgnilec zgnilec - 1 month ago 16
C# Question

How to allocate memory with a 16 byte alignment?

I use

Marshal.GlobalHAlloc
to allocate memory. As documentation says: "This method exposes the Win32 LocalAlloc function from Kernel32.dll.".
GlobalAlloc
's documentation says it will be 8 byte aligned but
LocalAlloc
don't say anything about align.

For example I want to allocate 1024 bytes and ensure it is aligned by 16. Will it work when I allocate 1024+16 bytes then I check pointer % 16? If result is 0 it means memory is aligned, when it is not 0, I just increment pointer to fit my expectations. The problem is I don't know, if I have aligned pointer it is really aligned in physical memory?

Answer

All Windows heap allocators align by 8. You can fix that by over-allocating and adjusting the pointer, like this:

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