C语言json-c库 json字符串清理内存问题

1、**json_object_to_json_string()、json_object_put()**函数

cpp 复制代码
json_object *json = NULL;
const char *json_str;

json_str = json_object_to_json_string(json);
json_object_put(json);//清除内存

查看json_object 结构可知:json_str 字符串的地址指向的是该结构体中printbuf *_pb 指向的地址,而该地址正是存储json对象转换后的字符串内存区域地址

cpp 复制代码
struct json_object
{
  enum json_type o_type;
  json_object_delete_fn *_delete;
  json_object_to_json_string_fn *_to_json_string;
  int _ref_count;
  struct printbuf *_pb;
  union data {
    json_bool c_boolean;
    double c_double;
    int64_t c_int64;
    struct lh_table *c_object;
    struct array_list *c_array;
    struct {
        char *str;
        int len;
    } c_string;
  } o;
};

调用函数json_object_put() 函数清理json 结构体的时候,就json_str 的内存一并清理了,因为不需要自己再专门清理字符串json_str

cpp 复制代码
struct printbuf {
  char *buf;
  int bpos;     //buf中已经使用的数量
  int size;     //buf的size
};

2、cJSON_Print、cJSON_Delete

在开源项目cJSON中,cJSON结构体并没有像上述json_object结构体中的printbuf *_pb,因此需要自己释放字符串的内存地址。字符串格式化函数调用后返回的字串内存,需要专门调用free函数释放掉

cpp 复制代码
/* The cJSON structure: */
typedef struct cJSON {
	struct cJSON *next,*prev;	/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
	struct cJSON *child;		/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */

	int type;					/* The type of the item, as above. */

	char *valuestring;			/* The item's string, if type==cJSON_String */
	int valueint;				/* The item's number, if type==cJSON_Number */
	double valuedouble;			/* The item's number, if type==cJSON_Number */

	char *string;				/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
cpp 复制代码
cJSON *pJsonRoot = cJSON_CreateObject();
char* strJson = cJSON_Print(pJsonRoot);
if (NULL != pJsonRoot)
{
	cJSON_Delete(pJsonRoot);
}
printf(strJson);
free(strJson);

参考:【C/C++业务】cJSON总结与使用

json-c-0.9库解析

相关推荐
万事可爱^1 小时前
GitHub爆火开源项目——RustScan深度拆解
c语言·开发语言·rust·开源·github·rustscan
冉佳驹2 小时前
数据结构 ——— 八大排序算法的思想及其实现
c语言·数据结构·排序算法·归并排序·希尔排序·快速排序·计数排序
异步的告白4 小时前
C语言-数据结构-2-单链表程序-增删改查
c语言·开发语言·数据结构
超级无敌大学霸4 小时前
二分查找和辗转相除法
c语言·算法
云知谷6 小时前
【软件测试】《集成测试全攻略:Mock/Stub 原理 + Postman/JUnit/TestNG 实战》
c语言·开发语言·c++·软件工程·团队开发
864记忆7 小时前
Qt 对 JSON和XML文件的操作详解
xml·qt·json
小龙报8 小时前
《算法通关指南C++编程篇 --- 初阶函数递归专题》
c语言·开发语言·c++·算法·创业创新·学习方法·visual studio
星轨初途9 小时前
《数据结构二叉树之堆 —— 优先队列与排序的高效实现(2)(下)》
c语言·开发语言·数据结构·经验分享·笔记·性能优化
Shylock_Mister9 小时前
ARM与x86交叉编译实战排错指南
linux·c语言·arm开发
x***01069 小时前
使用 MySQL 从 JSON 字符串提取数据
mysql·oracle·json