Is it legal to access a pointer type through a void **
?
I've looked over the standards quotes on pointer aliasing but I'm still unsure on whether this is legal C or not:
int *array;
void **vp = (void**)&array;
*vp = malloc(sizeof(int)*10);
Trivial example, but it applies to a more complex situation I'm seeing.
It seems that it wouldn't be legal since I'm accessing an int *
through a variable whose type is not int *
or char *
. I can't come to a simple conclusion on this.
Related:
Pointer to different types can have different sizes.
You can store a pointer to any type into a
void *
and then you can recover it back but this means simply that avoid *
must be large enough to hold all other pointers.Treating a variable that is holding an
int *
like it's indeed avoid *
is instead, in general, not permitted.Note also that doing a cast (e.g. casting to
int *
the result ofmalloc
) is something completely different from treating an area of memory containing anint *
like it's containing avoid *
. In the first case the compiler is informed of the conversion if needed, in the second instead you're providing false information to the compiler.On X86 however they're normally the same size and you're safe if you just play with pointers to data (pointers to functions could be different, though).
About aliasing any write operation done through a
void *
or achar *
can mutate any object so the compiler must consider aliasing as possible. Here however in your example you're writing through avoid **
(a different thing) and the compiler is free to ignore potentially aliasing effects toint *
.