forkachild / C-Simple-JSON-Parser

Extremely lightweight, easy-to-use & blazing fast JSON parsing library written in pure C
https://forkachild.github.io/C-Simple-JSON-Parser/
MIT License
45 stars 16 forks source link

JSON_ELEMENT_TYPE_NULL should be 0 #23

Open KoboldSoftware opened 4 months ago

KoboldSoftware commented 4 months ago

When passing an unitialized (or zero'ed) json_element_t to json_free()

typed(json_element) root_element = { 0 }; ... do something, maybe fail along the way ... json_free(&root_element);

it assumes JSON_ELEMENT_TYPE_STRING and calls free(root_element.value.as_string). While calling free(NULL) is valid and does nothing, it would be more intuitive to change the enum

from typedef enum json_element_type_e { JSON_ELEMENT_TYPE_STRING = 0, JSON_ELEMENT_TYPE_NUMBER, JSON_ELEMENT_TYPE_OBJECT, JSON_ELEMENT_TYPE_ARRAY, JSON_ELEMENT_TYPE_BOOLEAN, JSON_ELEMENT_TYPE_NULL } typed(json_element_type);

to typedef enum json_element_type_e { JSON_ELEMENT_TYPE_NULL = 0, JSON_ELEMENT_TYPE_STRING, JSON_ELEMENT_TYPE_NUMBER, JSON_ELEMENT_TYPE_OBJECT, JSON_ELEMENT_TYPE_ARRAY, JSON_ELEMENT_TYPE_BOOLEAN } typed(json_element_type);

as to avoid further confusion and a potential crash if the value happens to be non-NULL. That way json_free() will not call free() on the invalid element.

The initialization typed(json_element) root_element = { 0 }; may only set the type to 0 but leave the value uninitialized, depending on the C standard. With C99 the whole struct is memset to 0.

forkachild commented 2 weeks ago

This does look intuitive. You can open an MR.