void pointers as arguments and return values to standard functions
suggest changevoid*
is a catch all type for pointers to object types. An example of this in use is with the malloc
function, which is declared as
void* malloc(size_t);
The pointer-to-void return type means that it is possible to assign the return value from malloc
to a pointer to any other type of object:
int* vector = malloc(10 * sizeof *vector);
It is generally considered good practice to not explicitly cast the values into and out of void pointers. In specific case of malloc()
this is because with an explicit cast, the compiler may otherwise assume, but not warn about, an incorrect return type for malloc()
, if you forget to include stdlib.h
. It is also a case of using the correct behavior of void pointers to better conform to the DRY (don’t repeat yourself) principle; compare the above to the following, wherein the following code contains several needless additional places where a typo could cause issues:
int* vector = (int*)malloc(10 * sizeof int*);
Similarly, functions such as
void* memcpy(void *restrict target, void const *restrict source, size_t size);
have their arguments specified as void *
because the address of any object, regardless of the type, can be passed in. Here also, a call should not use a cast
unsigned char buffer[sizeof(int)];
int b = 67;
memcpy(buffer, &b, sizeof buffer);