colin
colin

Reputation: 41

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

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;

Upvotes: 2

Views: 904

Answers (3)

FSMaxB
FSMaxB

Reputation: 2490

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

Upvotes: 1

lulyon
lulyon

Reputation: 7225

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.

Upvotes: 2

rakeshNS
rakeshNS

Reputation: 4257

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.

Upvotes: 2

Related Questions