by phire · 4mo ago · 0 comments
Malloc doesn't know the required alignment (because has no idea what the type is, everything is cast through void). So all malloc implementations have a minimum alignment guarantee. Typically 16 bytes these days on x86, as that means even 128bit SSE values will end up aligned by default.
You couldn't go below the sizeof(void
) anyway, the backpointer needs to aligned too.The padding only happens when you use memalign or aligned_malloc to specify a much larger alignment.
However, the pointer to metadata is not really necessary.
The associated metadata could be stored in a table, and the index of the metadata could be computed from the offset of the pointer returned by malloc to the start of the heap (possibly using a hash function).
The ancient versions of the Microsoft C/C++ compilers were using a malloc with inline metadata. I have no idea if they replaced this more recently.
But most C code out there assumes malloc will always return something that is at least aligned to sizeof(void *), it's very rare to see aligned_alloc. So how is your alloc allocation going to know when it can get away with a smaller alignment?
Even if you are on a cpu that doesn't fault on unaligned memory access, any malloc implementation that doesn't align by default will have serious disadvantages in any benchmarks. IMO, There is no good reason to use an unaligned backpointer.
Fun story. Back in the early 2000s, my Delphi OpenGL program randomly crashed when I tried to use vertex buffers. I spent a lot of time checking this and that, before I realized it might be an alignment issue.
Sure enough, Delphi memory allocator at the time only provided 4-byte alignment, while NVIDIA's drivers used aligned SSE instructions which require 16-byte alignment.
So, had to manually align the buffers before passing them to OpenGL.
However Microsoft's malloc at the time was indeed returning 16-byte aligned buffers so they probably didn't notice it in internal testing.
[0] https://www.intel.com/content/www/us/en/docs/intrinsics-guid...