C - How to resolve memory leaks?

259 views Asked by At

Below is the part of script and the same is invoked from main function. If i comment out the below function, everything works fine without any memory leak issue, whereas by including this function, the process ends up with memory leak and eventually it stops over a span of 2 hrs.

void passRFIDInfo(int antenna_id, int peakRssi, char *fast_id, int reader_mac_flag, int data_accumulated_flag){

  if (reader_mac_flag == 0){
    struct ifreq s;

      int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);


    strcpy(s.ifr_name, "eth0");
    if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;

    for (i = 0; i < 6; ++i){
      unsigned char data  =  s.ifr_addr.sa_data[i];
      sprintf(reader_mac+(i*2), "%02x", data);
    }
    reader_mac[12] = '\0';
    }
  }

  char uniqueID[40];



  char *antennaID = (char*)malloc(2);
  snprintf(antennaID, sizeof(antennaID), "%d", antenna_id);


  strcpy(uniqueID, reader_mac);

  strcat(uniqueID, ".");
  strcat(uniqueID, antennaID);
  strcat(uniqueID, ".");
  strcat(uniqueID, fast_id);



  int json_size = json_object_size(root);

  if (data_accumulated_flag==1 && json_size!=0) 
  {

    sendMQTT(rfid_json_dict);

    free(rfid_json_dict);      
    json_decref(root);

    json_t *root = json_object();  
    char *rfid_json_dict;
  }

  json_object_set_new( root, uniqueID, json_integer(peakRssi));
  rfid_json_dict = json_dumps(root, 0);

  printf("rfid_json_dict ::%s\n",rfid_json_dict);
  printf("\n");

}

Before the program executes, the available memory in an embedded linux platform is,

>show system cpu
Status='0,Success'
TotalMemory='62304256'
FreeMemory='18621122'
CPUUtilization='3'

As the execution continues for 2 hrs and so, the FreeMemory keeps going down and eventually at the end of 3 hrs, the process killed automatically. How to resolve such kind of issue?

1

There are 1 answers

0
Jordan Bancino On

Just as it was pointed out in the comments, you're missing a call to free() on antennaID. So you malloc() memory for it, but then it's never freed. So it just keeps piling up.

The general rule is that for every call to malloc(), there should be a call to free(). At least, that's how I learned, and that's what makes the most sense to me. As soon as you're done using a variable, you should free() it. Briefly going through that code, it doesn't look like antennaID ever leaves the function? So you should be good to just free it before the function returns.