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.
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.
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.
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().
Definition and Usage The void keyword specifies that a method should not have a return value.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With