Add function to traverse json tree and free all memory allocations
This commit is contained in:
@@ -110,6 +110,52 @@ void print_json(const jentity_t *entity, u32 indent) {
|
||||
}
|
||||
}
|
||||
|
||||
void free_json(jentity_t **entity) {
|
||||
if (!(*entity)) {
|
||||
return;
|
||||
}
|
||||
|
||||
jentity_t *entt_ptr = *entity;
|
||||
|
||||
dstr_t *key = NULL;
|
||||
const jval_t *value = NULL;
|
||||
|
||||
if (entt_ptr->type == JENTITY_SINGLE) {
|
||||
value = &(entt_ptr->value);
|
||||
} else {
|
||||
key = entt_ptr->pair.key;
|
||||
value = &(entt_ptr->pair.value);
|
||||
}
|
||||
|
||||
if (key) {
|
||||
dstr_free(&(entt_ptr->pair.key));
|
||||
}
|
||||
|
||||
switch (value->type) {
|
||||
case JVAL_COLLECTION:
|
||||
if (value->collection->begin) {
|
||||
free_json(&(value->collection->begin));
|
||||
}
|
||||
|
||||
free(value->collection);
|
||||
|
||||
break;
|
||||
case JVAL_STRING:
|
||||
dstr_free(&(entt_ptr->pair.value.string));
|
||||
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (entt_ptr->next) {
|
||||
free_json(&(entt_ptr->next));
|
||||
}
|
||||
|
||||
free(*entity);
|
||||
*entity = NULL;
|
||||
}
|
||||
|
||||
jcoll_t *get_collection_from_entity(const jentity_t *entity) {
|
||||
return entity->type == JENTITY_SINGLE ? entity->value.collection
|
||||
: entity->pair.value.collection;
|
||||
|
||||
@@ -23,5 +23,7 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
print_json(root, 2);
|
||||
|
||||
free_json(&(root));
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user