0

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;
}
2

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

so basically, void ** is to make it become array. And the reason to make it become array is because we need to store the allocated pointer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.