Search code examples
cmemoryalignmentmalloc

Implement aligned_malloc using malloc in C


Question: why do we declare p2 as void **? why not p2*?

we are returning p2, but our return function type is void *. This doesn't make any sense. Compiler will say unmatch return type.

void *aligned_malloc(size_t required_bytes, size_t alignment) {
    void *p1;
    void **p2;
    int offset=alignment-1+sizeof(void*);
    p1 = malloc(required_bytes + offset);               // the line you are missing
    p2=(void**)(((size_t)(p1)+offset)&~(alignment-1));  //line 5
    p2[-1]=p1; //line 6
    return p2;
}

Solution

  • void** can be implicitly converted to void*, so there shouldn't be a type problem.

    The reason it's declared void** is to make it convenient to store the allocated pointer just in front of it.

    It works like this code, which uses another variable:

    void *aligned_malloc(size_t required_bytes, size_t alignment) {
        void *p1;
        void *p2;
        void **p3;
        int offset=alignment-1+sizeof(void*);
        p1 = malloc(required_bytes + offset);
        p2= (void*)(((size_t)(p1)+offset)&~(alignment-1));
        p3 = (void**) p2; 
        p3[-1]=p1;
        return p2;
    }