Topics / Pointers & Memory / Q3
What is a void pointer?
Short answer: void * is a generic pointer that can hold the address of any object type. You cannot dereference it or do arithmetic on it directly in standard C; you first convert it to a pointer of the real type. In C it converts implicitly to and from any object pointer type, which is why malloc returns void * and needs no cast.
void *mem = malloc(16); /* no cast needed in C (needed in C++) */
uint8_t *bytes = mem; /* implicit conversion */
int cmp_int(const void *a, const void *b) /* qsort comparator */
{
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
Where it is used
- Generic memory functions:
memcpy(void *dst, const void *src, size_t n),memset. - Generic algorithms:
qsort,bsearch. - Callback "context" arguments, so one callback can serve many instances:
void (*cb)(void *ctx). - RTOS APIs: FreeRTOS task parameters (
void *pvParameters) and queue items. - Opaque handles in APIs.
Cautions
- The compiler cannot check the type behind a
void *; converting it back to the wrong type is a bug the compiler will not catch. - Function pointers are not guaranteed to convert to
void *(POSIXdlsymrelies on it; on most platforms it works). void *arithmetic (p + 1) is a GCC extension that treats the size as 1; write(uint8_t *)p + 1for portable code.- When converting
void *to a type with stricter alignment, the address must actually be suitably aligned.