内存无法在C中释放

时间:2016-04-17 06:15:55

标签: c

当我在while循环中调用它时,以下wifi_json()方法会不断增加内存以进行测试。是因为方法中使用的结构没有被释放,或者我没有使用免费方法来正确释放内存?

#include "MiCO.h" 
#include "json_c/json.h"
#define os_json_log(M, ...) custom_log("JSON", M, ##__VA_ARGS__)
void wifi_json()
{
  os_json_log("%s","start");
  struct json_object *recv_json_object_device_wifi=NULL;
  recv_json_object_device_wifi=json_object_new_object();      

  struct json_object *recv_json_object_array_wifi=NULL;
  recv_json_object_array_wifi=json_object_new_array(); //wifi array

  struct json_object *recv_json_object_wifi=NULL; //recv wifi
  recv_json_object_wifi=json_object_new_object();

  struct json_object *wifi_object=NULL; //wifi
  wifi_object=json_object_new_object();

  //wifi
 json_object_object_add(wifi_object, "connected", json_object_new_string("1"));    
 json_object_object_add(wifi_object, "strength", json_object_new_string("60")); 
 json_object_object_add(wifi_object, "ip", json_object_new_string("60"));
 json_object_object_add(wifi_object, "mac", json_object_new_string("60"));
 json_object_object_add(wifi_object, "ssid", json_object_new_string("60"));
 json_object_object_add(recv_json_object_wifi,"WIFI",wifi_object);

 json_object_array_add(recv_json_object_array_wifi,recv_json_object_wifi);
 json_object_array_add(recv_json_object_array_wifi,recv_json_object_wifi);
 json_object_array_add(recv_json_object_array_wifi,recv_json_object_wifi);

 json_object_object_add(recv_json_object_device_wifi,"WIFI_Info",recv_json_object_array_wifi);
 os_json_log("%s",json_object_to_json_string(recv_json_object_device_wifi));

 free(recv_json_object_device_wifi);
 recv_json_object_device_wifi=NULL;

 free(recv_json_object_array_wifi);
 recv_json_object_array_wifi=NULL;

 json_object_put(recv_json_object_wifi);
 json_object_put(wifi_object);


 json_object_put(recv_json_object_array_wifi);
 json_object_put(recv_json_object_device_wifi);
}
int application_start( void )
{  
 while(1)
 {
    wifi_json(); 
    os_json_log("Free memory has %d bytes", MicoGetMemoryInfo()->free_memory) ;
   }
  }

3 个答案:

答案 0 :(得分:2)

您还需要释放这两者创建的内存:

struct json_object *recv_json_object_wifi=NULL; //recv wifi
recv_json_object_wifi=json_object_new_object();

struct json_object *wifi_object=NULL; //wifi
wifi_object=json_object_new_object();

答案 1 :(得分:1)

我认为您的问题出在os_json_log("%s",json_object_to_json_string(recv_json_object_device_wifi));

您应该指定一个指针并稍后将其释放。

const char *str = json_object_to_json_string(recv_json_object_device_wifi);
os_json_log("%s", str);
free(str);

此外,只是做一个

json_object_put(recv_json_object_device_wifi);

足够了,因为这是添加所有其他对象的根对象。无需为其任何子女致电json_object_put

答案 2 :(得分:0)

请尝试使用此方法释放json对象的内存“json_object_object_del()”

json_object_object_del(recv_json_object_wifi); recv_json_object_wifi = NULL; json_object_object_del(wifi_object); wifi_object = NULL;