CJson内存泄漏注意事项

593 阅读1分钟

说明

VC6.0中实测!ASSIC编码。

数据

 //设备配置信息
 struct ConfigurationInformation
 {
     std::string id;         //设备id
     std::string name;       //设备name
     std::string type;       //设备类型
     std::string ip;         //设备ip地址
     UINT  port;             //设备端口号
 ​
 ​
     ConfigurationInformation() {
         id = " ";
         name = " ";
         type = " ";
         ip = " ";
         port = 0;
     }
 ​
 };
 typedef ConfigurationInformation CfgInfo;

错误用法:导致内存泄漏

 std::string CfgInfoToJson(CfgInfo cfgInfo)
 {
     cJSON* cjson;
     cjson = cJSON_CreateObject();
     cJSON_AddStringToObject(cjson, "id", cfgInfo.id.c_str());
     cJSON_AddStringToObject(cjson, "name", cfgInfo.name.c_str());
     cJSON_AddStringToObject(cjson, "type", cfgInfo.type.c_str());
     cJSON_AddStringToObject(cjson, "ip", cfgInfo.ip.c_str());
     cJSON_AddNumberToObject(cjson, "port", cfgInfo.port);
     char* strRet = cJSON_Print(cjson);              //此处会出现内存泄漏呀!!!
     cJSON_Delete(cjson);
     return strRet;
 }

正确用法

 //配置信息生成json
 std::string CfgInfoToJson(CfgInfo cfgInfo)
 {
     cJSON* cjson;
     cjson = cJSON_CreateObject();
     cJSON_AddStringToObject(cjson, "id", cfgInfo.id.c_str());
     cJSON_AddStringToObject(cjson, "name", cfgInfo.name.c_str());
     cJSON_AddStringToObject(cjson, "type", cfgInfo.type.c_str());
     cJSON_AddStringToObject(cjson, "ip", cfgInfo.ip.c_str());
     cJSON_AddNumberToObject(cjson, "port", cfgInfo.port);   
     char* strRet = cJSON_Print(cjson);
     cJSON_Delete(cjson);
 ​
     std::string ret = strRet;
     delete strRet;
     return ret;
 }

\