C-Simple-JSON-Parser icon indicating copy to clipboard operation
C-Simple-JSON-Parser copied to clipboard

json_free() guidance

Open milankowww opened this issue 1 year ago • 1 comments
trafficstars

What is the proper guideline for json_free() to prevent memory leaks? It seems to me from the recursive nature of json_free() that it is sufficient to call it for the topmost object, but still, in the README example you don't call it on any error, which leads me to believe the example contains a memory leak (of course the program exits but that's not the point).

Is it "call it on the value of the topmost unwrap but only if it was successful", or is it something else?

milankowww avatar Apr 17 '24 18:04 milankowww

Yes, your assumption is correct. It will leak memory on failure. This can be resolved in 2 ways:

  1. Calling json_free() at fallible points in each parsing step.
  2. Sizing the JSON before parsing. This will solve the following:
    1. Fail without allocating anything.
    2. Have one monolithic allocation, avoiding redundant segmentation (due to multiple allocations).
    3. Contiguous cache-friendly memory access.

I would strongly prefer solution 2. What are your thoughts on this?

whyisitworking avatar Apr 17 '24 20:04 whyisitworking