Memory leak in particle.subscribe() [SOLVED]

Hi,
I am working on a solar monitor system. One photon is publishing a string that I read on the other photon.

void ParsePV(const char *event1, const char *data1)
{
  char* Controller1 = strtok(strdup(data1), ",");
  PV = atoi(strtok(NULL, ","));
  counter = atoi(strtok(NULL, ","));
}

The code above works but produces a ‘memory leak’, leading to a wifi disconnect after 1hr15min. A system reset solves this, but it is not very elegant. By commenting out my particle.subscribe I have no memory leak.

I declared the controller1 string globally by moving this to the beginning of the sketch:

char* Controller1;

and

 void ParsePV(const char *event1, const char *data1)
    {
      Controller1 = strtok(strdup(data1), ",");
      PV = atoi(strtok(NULL, ","));
      counter = atoi(strtok(NULL, ","));
    }

now there is a smaller memory leak. I tried moving data1 and event1 to the global variables as well:

char*event1;
char*data1;
char* Controller1;

and

void ParsePV(event1, data1)
{
  //char* 
  Controller1 = strtok(strdup(data1), ",");
  PV = atoi(strtok(NULL, ","));
  counter = atoi(strtok(NULL, ","));
}

But now it doesn’t compile because event1 and data1 are not declared in this scope.
I know it has something to do with the strings, but I don’t understand how to do this. Maybe cleanup the memory allocated to the string after each read/process to integers?

Cheers,
eric

The strdup() creates a copy of the string on the heap, but you never free() the allocated memory. But even if you did, you’d produce heap fragmentation.

I’d rather go for a solution along this line

void ParsePV(const char *event1, const char *data1)
{
  char copyData[strlen(data1)+1];
  strcpy(copyData, data1);
  char* Controller1 = strtok(copyData, ","); // this needs to be fixed, since copyData will vanish
  PV = atoi(strtok(NULL, ","));
  counter = atoi(strtok(NULL, ","));
}

If you need Controller1 globally accessible (which would not seem so judging by your first snippet), you’d need to declare it like

char Controller1[expectedMaxLen];

and copy the string over to that via

  strncpy(Controller1, strtok(copyData, ",")), sizeof(Controller1)-1);
2 Likes

Great, tried and works! I have to study your reply a bit longer to understand why this is working, but consider this as SOLVED!

thanks a lot,
Eric

4 Likes

@bieric Glad you got this working! Thanks for the help @ScruffR!