Reputation: 2531
I am writing a program in C, on an x86 and/or 64-bit Windows platform. I have used VirtualAlloc
to allocate a large chunk of memory. Now in my program I am going to divvy that memory space up among various parts of my program at runtime using what amounts to a memory allocator that I wrote myself. The data that will be packed into this chunk of memory includes things like bitmaps, wav files, etc. The Windows constant MEMORY_ALLOCATION_ALIGNMENT
is defined as 8 on 32-bit versions of the OS and 16 on 64-bit versions. My question is, do I still care about aligning this data along 8 or 16 byte boundaries if I've already allocated a contiguous (already aligned) chunk from VirtualAlloc
? It is trivial to add the padding bytes to my allocator if necessary, but I don't know if I really need to.
To be clear, let's say I have
void* Chunk = VirtualAlloc(NULL, 33554432, MEM_RESEVE | MEM_COMMIT, PAGE_READWRITE);
So now I have 32MB of memory that the OS has already aligned for me. If I subdivide that 32MB chunk of memory up myself among various pieces of data, should those subdivided regions of memory also be aligned on 8 or 16 byte boundaries?
Upvotes: 0
Views: 268
Reputation: 144780
Whether the chunks of that memory block need a particular alignment depends on how they will be accessed by the code. If you do not know how the code accesses this memory, you should align the chunks by rounding the offset up to a multiple of MEMORY_ALLOCATION_ALIGNMENT
. Otherwise, you might invoke undefined behavior if the code accessing the chunk makes an invalid assumption and accesses the unaligned memory with some instructions that command a specific alignment.
On the x86 architecture, with common settings, byte, word, double and quad word accesses can be made on misaligned adresses, but MMX and AVX instructions do require 16 byte alignment and generate exceptions if done on unaligned addresses.
Upvotes: 1