This is not homework, this is purely for my own personal education.
I couldn\'t figure out how to implement an aligned malloc so looked online and found this website. Fo
You need an offset if you want to support alignments beyond what your system's malloc()
does. For example if your system malloc()
aligns to 8 byte boundaries, and you want to align to 16 bytes, you ask for 15 bytes extra so you know for sure you can shift the result around to align it as requested. You also add sizeof(void*)
to the size you pass to malloc()
to leave room for bookkeeping.
~(alignment - 1)
is what guarantees the alignment. For example if alignment is 16, then subtract 1 to get 15, aka 0xF, then negating it makes 0xFF..FF0 which is the mask you need to satisfy the alignment for any returned pointer from malloc()
. Note that this trick assumes alignment is a power of 2 (which practically it normally would be, but there really should be a check).
It's a void**
. The function returns void*
. This is OK because a pointer to void is "A pointer to any type," and in this case that type is void*
. In other words, converting void*
to and from other pointer types is allowed, and a double-pointer is still a pointer.
The overall scheme here is to store the original pointer before the one that's returned to the caller. Some implementations of standard malloc()
do the same thing: stash bookkeeping information before the returned block. This makes it easy to know how much space to reclaim when free()
is called.
All that said, this sort of thing is usually not useful, because the standard malloc()
returns the largest alignment on the system. If you need alignment beyond that, there may be other solutions, including compiler-specific attributes.