zgnilec zgnilec - 1 year ago 128
C# Question

How to allocate memory with a 16 byte alignment?

I use

to allocate memory. As documentation says: "This method exposes the Win32 LocalAlloc function from Kernel32.dll.".
's documentation says it will be 8 byte aligned but
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download