json.h icon indicating copy to clipboard operation
json.h copied to clipboard

Malloc/Free and how to handle freeing of memory

Open f1nalspace opened this issue 1 month ago • 0 comments

Nice library! I really love how memory is handled there:

  • Computing the entire size upfront
  • Allocate a single block of memory
  • Do the actual parsing into that memory block
  • Use can traverse by type and payload

But i have a few ideas how to improve on that.

First, there is no free or release function, that would release the entire memory block. Please add one function that would free() the "dom" memory. Of course this would require a second callback for the user to pass in free_func_ptr.

Second, the custom allocator api is kind of "too simple" and i have a idea of a much cleaner and less error prone version:

// Defining function definitions it as a macro has the advantage, that you can easily make stubs for default malloc/free and users can use that as well to use their own custom allocator

#define JSON_MEMORY_ALLOC_FUNC(name) void *name(void *userdata, const size_t size) typedef JSON_MEMORY_ALLOC_FUNC(json_memory_alloc_func);

#define JSON_MEMORY_FREE_FUNC(name) void name(void *userdata, void *ptr, const size_t allocatedsize) typedef JSON_MEMORY_FREE_FUNC(json_memory_free_func);

typedef struct json_memory_allocator_s { void* userdata; json_memory_alloc_func *alloc; json_memory_free_func *free; uintptr_t padding; // align to 16/32 bytes, depending on the architecture } json_memory_allocator_t;

Then json_parse_ex() would have a single argument: struct json_memory_allocator_s *mem_allocator instead and you can even store the entire struct into the json_parse_state_s.

This would be much cleaner and would work across all functions.

Lastly please double check any malloc() usages, there are a few places which does not allow to pass in a custom memory allocator, e.g. json_write_minified()

f1nalspace avatar Nov 22 '25 13:11 f1nalspace