cJSON: can't understand something of it's source code

825 views Asked by At

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;
3

There are 3 answers

0
rakeshNS On

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.

0
lulyon On

Those are function pointer initialization. For example:

static void *(*cJSON_malloc)(size_t sz) = malloc;

is equivalent to:

typedef void *(*cJSON_malloc_type)(size_t sz);
static cJSON_malloc_type cJSON_malloc = malloc;

I hope this is more understandable.

0
FSMaxB On

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:

  • Performance
  • Debugging
  • Security
  • Special Device Memory

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);
}