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

相关推荐
weixin_446023561 天前
C语言开发Win32程序太麻烦?微软不支持有3个原因
c语言·微软·mfc·win32程序·开发难度
程序员zgh1 天前
C/C++ 单元测试系统 构建
c语言·开发语言·c++·学习·单元测试
孬甭_1 天前
揭开指针的面纱(中)
c语言
草莓熊Lotso1 天前
【Linux系统加餐】 mmap 文件映射全解:从底层原理、API 到实战开发(含 malloc 模拟实现)
android·linux·运维·服务器·c语言·c++
深邃-1 天前
【C语言】-数据在内存中的存储(2):浮点数在内存中的存储
c语言·开发语言·数据结构·c++·算法·html5
智者知已应修善业1 天前
【51单片机利用外部中断编写程序用两个按键控制数码管显示从0到9,S1控制加计数0—9,S2控制减计数9—0。】
c语言·经验分享·笔记·算法·51单片机
cch89181 天前
Java vs C语言:编程语言终极对决
java·c语言·开发语言
智者知已应修善业1 天前
【51单片机实现0-7和8-1循环显示共阴数码管】2023-5-12
c语言·经验分享·笔记·算法·51单片机
C^h1 天前
c语言 链表学习笔记
c语言·学习·链表
笨笨饿1 天前
28_关于交叉学科的学习方法
linux·服务器·c语言·算法·学习方法·机械