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库解析

相关推荐
卿卿的产品经理日记2 小时前
【AI产品经理实战】Day 37|拆开 JSON 与 EXE:数据都有格式
人工智能·笔记·python·json·产品经理
iCxhust2 小时前
51单片机电力载波应用开发(九)51产品化
c语言·数据库·嵌入式硬件·mysql·51单片机·软件工程·c51
whbi2 小时前
基于阿里云的datax现有功能开发的一个可以自动生成.json的配置文件功能或者脚本
json
Logic1013 小时前
C语言/数据结构字符串题解:统计“chhc“子串权值总和——一次遍历模式匹配
c语言·数据结构·算法·字符串·时间复杂度·空间复杂度·ascii
mengzhi啊4 小时前
qt把结构体数据存入json文件
qt·json
m0_547486664 小时前
《数据结构 (C语言)》期末试卷及答案(10套)2026版
c语言·开发语言·数据结构
八月的雨季 最後的冰吻4 小时前
FFmepg-- 42-ffplay.c 线程安全机制深度分析
c语言·安全·ffmpeg
逐光者9335 小时前
滤波器的 R 与 C 如何选择:从截止频率到工程实践
c语言·开发语言·r语言
SelectDB技术团队5 小时前
VARIANT 列接入网关 JSON 日志:建表、导入、子列查询与物化的完整步骤
大数据·数据库·人工智能·elasticsearch·搜索引擎·json·apache doris
水饺编程5 小时前
第2章:Linux 基础,whoami 命令
linux·c语言·汇编