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

相关推荐
Bt年3 小时前
第十六届蓝桥杯 C/C++ B组 题解
c语言·c++·蓝桥杯
我命由我123455 小时前
STM32 开发 - stm32f10x.h 头文件(内存映射、寄存器结构体与宏、寄存器位定义、实现点灯案例)
c语言·开发语言·c++·stm32·单片机·嵌入式硬件·嵌入式
xyd陈宇阳5 小时前
嵌入式开发高频面试题全解析:从基础编程到内存操作核心知识点实战
c语言·数据结构·stm32·算法·面试
大魔王(已黑化)8 小时前
LeetCode —— 572. 另一棵树的子树
c语言·数据结构·c++·算法·leetcode·职场和发展
珹洺9 小时前
C++从入门到实战(十一)详细讲解C/C++语言中内存分布与C与C++内存管理对比
c语言·数据结构·c++
XiaoCCCcCCccCcccC9 小时前
Linux中线程池的简单实现 -- 线程安全的日志模块,策略模式,线程池的封装设计,单例模式,饿汉式单例模式,懒汉式单例模式
linux·c语言·c++·安全·单例模式·策略模式
南玖yy9 小时前
C++ 的未来战场:从技术深耕到职业破局
c语言·开发语言·c++·后端·c++未来
海绵宝宝的月光宝盒10 小时前
[stm32] 4-1 USART(1)
c语言·开发语言·笔记·stm32·单片机
Mr_Chenph19 小时前
真.从“零”搞 VSCode+STM32CubeMx+C <2>调试+烧录
c语言·stm32·嵌入式硬件
YuforiaCode19 小时前
第十六届蓝桥杯 2025 C/C++B组第一轮省赛 全部题解(未完结)
c语言·c++·蓝桥杯