When I read the code of cJSON, and have problem understanding the code:
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
As the others have already mentioned, these are function pointers. With those you can change the allocator and deallocator function at runtime.
There are many reasons why you would want to use a different allocator than malloc and free, for example:
Example allocator that prints every allocation and deallocation to stdout:
void *my_malloc(size_t size) {
void *pointer = malloc(size);
printf("Allocated %zu bytes at %p\n", size, pointer);
return pointer;
}
void my_free(void *pointer) {
free(pointer);
printf("Freed %p\n", pointer);
}
void change_allocators() {
cJSON_hooks custom_allocators = {my_malloc, my_free};
cJSON_InitHooks(custom_allocators);
}
This is just function pointers. By doing this way we can use 'cJSON_malloc' in place of malloc and cJSON_free in place of free.