Is it good practice to access a pointer variable by dereferencing a pointer to a pointer, which points to a different type or void
? Could this break strict aliasing rules? C and C++ have some differences in aliasing rules. In this question we focus on C. The other question considering C++ can be found here. In the following example a double*
is accessed as a void*
.
int create_buffer(void** ptr, ...)
{
*ptr = malloc(...);
...
}
int main(void)
{
double* buffer;
// The problematic code is here, double**
// is coerced to void**, which is later
// dereferenced by the function
create_buffer((void**)&buffer, ...);
...
}
Is the following any better:
// keeping void** just as an indicator in the interface
// that the pointer is pointing to a pointer to any type
// it could be replaced by just void*
int create_buffer(void** ptr, ...)
{
void* result = malloc(...);
memcpy((void*)ptr, &result, sizeof result);
}
I would rather write it like this, assuming you use the "int" to return some useful information to the caller that it can't do without:
Not answering your question, but you could manoeuvrer around the uncertainties you mention by just doing well defined stuff like: