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
implementation does work
Perhaps, but I wouldn't be too sure. IMO you'd be better off working from first principles. Right off the bat,
p1 = (void*)malloc
is a red flag. malloc
returns void
. In C, any pointer can be assigned from void *
. Casting from malloc
is usually considered bad form because any effect it has can only be bad.
Why we need an offset
The offset provides room to stash the pointer returned by malloc
, used later by free
.
p1
is retrieved from malloc
. Later, it has to be provide to free
to be released. aligned_malloc
reserves sizeof(void*)
bytes at p1
, stashes p1
there, and returns p2
(the first "aligned" address in the block that p1
points to). Later, when the caller passes p2
to aligned_free
, it converts p2
in effect to void *p2[]
, and fetches the original p1
using -1 as an index.
What does anding with ~(alignment - 1) accomplish
It's what puts p2
on the boundary. Say alignment is 16; alignment -1
is 15, 0xF. ~OxF
is all bits on except the last 4. For any pointer P
, P & ~0xF
will be a multiple of 16.
p2
is a double pointer.
pointer schmointer. malloc
returns void*
. It's a block of memory; you address it as you will. You wouldn't blink at
char **args = calloc(7, sizeof(char*));
to allocate an array of 7 char *
pointers, would you? The code picks some "aligned" location at least sizeof(void*)
bytes from p1
and, for the purposes of free
, treats it as void **
.
What is the general approach
There is no one answer. Best is probably to use a standard (or popular) library. If you build atop malloc
, allocating enough to keep the "real" pointer and returning an aligned one is pretty standard, although I would code it differently. The syscall mmap
returns a page-aligned pointer, which will satisfy most criteria for "aligned". Depending on need, that might be better or worse than piggybacking on malloc
.