Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a void* and *(void**)?

Tags:

c++

pointers

I was programming an aligned_malloc implementation in C++ and mainly use the following code, which can be found in various places on the Interwebs, including SO:

void * aligned_malloc(size_t size, int align) {
    if (align < 0) {
        return NULL;
    }

    void *ptr;
    void *p = malloc(size + align - 1 + sizeof(void*));

    if (p != NULL) {
        ptr = (void*) (((ptrdiff_t)p + sizeof(void*) + align -1) & ~(align-1));
        *((void**)((ptrdiff_t)ptr - sizeof(void*))) = p;
        return ptr;
    }
    return NULL;
}

void aligned_free(void *p) {
    void *ptr = *((void**)((ptrdiff_t)p - sizeof(void*)));
    free(ptr);
    return;
}

I get the *(void**) in the aligned_malloc. My misunderstanding is with the cast in the aligned_free. Since we just want the value and don't have to assign to it why not use

void *ptr = ((void*)((ptrdiff_t)p - sizeof(void*)));

instead of

void *ptr = *((void**)((ptrdiff_t)p - sizeof(void*)));

I thought it was the same but when I tried the first one with an alignment of 64 it gave me an error, but when I tried the second cast the program worked correctly. So what is the difference between the two? I left out the proper C++ casts for the sake of readability.

like image 983
toteload Avatar asked Jun 02 '14 08:06

toteload


People also ask

What is the difference between void and void *?

The basic difference between both ( Void & void ) is that void is a primitive type while Void , a reference type that inherits from the Object . Although none of them has any possible values, both are of different types.

What is void and void?

1 : containing nothing : empty void space. 2 : being without something specified : devoid a person void of common sense. 3 : of no legal force or effect a void contract.

Is void the same as ()?

It seems like () and Void both mean exactly the same thing (the type Void) when used in the context of a type declaration, but in all other contexts, () instead means an instance of the type Void, ie the same as Void().

What is void in a method?

Definition and Usage The void keyword specifies that a method should not have a return value.


1 Answers

Let us simplify the code:

int x = 7;
void * p = &x;
void * q = &p;

And now let us draw a diagram:

  +---+
x | 7 |
  +---+
    ^ 
    |
  +-|-+
p | * |
  +---+
    ^ 
    |
  +-|-+
q | * |
  +---+

Do you see how p and q are not equal? If you have q, and you want to get to p, you have to dereference q. But since a void* cannot be dereferenced, you have to promise the type system that it will find another pointer after the dereference, hence the cast to void** before the dereference.

assert(q != p);
assert(*(void**)q == p);
like image 182
fredoverflow Avatar answered Oct 01 '22 17:10

fredoverflow