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. For the ease of reading I will post the code below:
#include <stdlib.h>
#include <stdio.h>
void* aligned_malloc(size_t required_bytes, size_t alignment)
{
void* p1; // original block
void** p2; // aligned block
int offset = alignment - 1 + sizeof(void*);
if ((p1 = (void*)malloc(required_bytes + offset)) == NULL)
{
return NULL;
}
p2 = (void**)(((size_t)(p1) + offset) & ~(alignment - 1));
p2[-1] = p1;
return p2;
}
void aligned_free(void *p)
{
free(((void**)p)[-1]);
}
void main (int argc, char *argv[])
{
char **endptr;
int *p = aligned_malloc (100, strtol(argv[1], endptr, 10));
printf ("%s: %p\n", argv[1], p);
aligned_free (p);
}
The implementation does work, but I honestly can't figure out how it works.
Here is what I can't understand:
- Why we need an offset?
- What does anding with
~(alignment - 1)
accomplish p2
is a double pointer. How come we can return it from a function that is supposed to return only a single pointer?- What is the general approach to solve this problem?
Any help is really appreciated.
EDIT
This is not a duplicate of How to allocate aligned memory only using the standard library? because I also need to know how to free aligned memory.